How to fetch JSON using NSURLSession

In this tutorial I will discuss about iOS application that fetches some JSON from a web API

While building this application we will be following:

  • Functions
  • Arrays
  • Dictionaries
  • NSURLSession

Open Xcode

Let’s open Xcode and build a single view application.

Go to ViewController.swift.

Your default ViewController.swift should appear like this:

import UIKit

class ViewController: UIViewController {
 
 override func viewDidLoad() {
 super.viewDidLoad()
 // Do any additional setup after loading the view, typically from a nib.
 
 }
 
 override func didReceiveMemoryWarning() {
 super.didReceiveMemoryWarning()
 // Dispose of any resources that can be recreated.
 }
 
}

Let’s start writing some code.

Initiate by creating a function called parseJSON() after viewDidLoad().

This is where we are going to have our network logic to clutch our JSON from the web API.

Let’s describe our url:

func parseJSON () {
 
 let url = URL(string: "https://api.myjson.com/bins/vi56v")
 
}

We are following let  alternative of var because we won’t be manipulating this url.

Currently let’s add NSURLSession:

func parseJSON () {

let url = URL(string: "https://api.myjson.com/bins/vi56v")

let task = URLSession.shared.dataTask(with: url!) {(data, response, error ) in

}

}

With this task block is where we will ensure for errors and put our data into an array to populate our table.

Let’s check for any errors & if theres any empty data:

 func parseJSON () {
 
 let url = URL(string: "https://api.myjson.com/bins/vi56v")
 let task = URLSession.shared.dataTask(with: url!) {(data, response, error ) in
 
 guard error == nil else {
 print("returned error")
 return
 }
 
 guard let content = data else { 
 print("No data")
 return
 }
 } 
}

Now we need to convert our JSON to NSDictionary with JSONSerialization.

func parseJSON () {
 
 let url = URL(string: "https://api.myjson.com/bins/vi56v")
 let task = URLSession.shared.dataTask(with: url!) {(data, response, error ) in

guard error == nil else {
 print("returned error")
 return
 }

if error != nil {

}else {
 print("returned error")
 }

guard let content = data else {

print("No data")
 return
 }

guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
 print("Not containing JSON")
 return
 }

}

}

Now what we have a NSDictionary, we preserve tap into “companies” key and put all the values into an NSMutableArray.

We then would loop into this array and include all value to a local defined array.

Let’s describe our local array.

import UIKit

class ViewController: UIViewController {
 
 var tableArray = [String] ()
 
...

Now that we have a local array definite we can go onto putting our “companies” into our tableArray.

if let array = json["companies"] as? [String] {
 self.tableArray = array
}
print(self.tableArray)

We require to include task.resume() outside our task block.

Appear like:

func parseJSON() {
let url = URL(string: "https://api.myjson.com/bins/vi56v")

let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in

guard error == nil else {
 print("returning error")
 return
 }

guard let content = data else {
 print("not returning data")
 return
 }


 guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
 print("Not containing JSON")
 return
 }

if let array = json["companies"] as? [String] {
 self.tableArray = array
 }

print(self.tableArray)

DispatchQueue.main.async {
 self.tableView.reloadData()
 }

}

task.resume()

}

Currently call parseJSON() in viewDidLoad and you should see the array in the console.

Last Update: October 8, 2018  

October 8, 2018   109   Nandini R    Web Services    
Total 0 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn