Today we will learn how to make a json call and parse it in swift 3. I have used a free  json API for this.

 

Here is the sample code for this.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

        callWebService()

        // 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.

    }

    

    

    func callWebService() -> Void {

        let apiLink = http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo”

        

        let task = URLSession.shared.dataTask(with: NSURL(string: apiLink)! as URL, completionHandler: { (data, response, error) -> Void in

            do{

                var jsonDict :NSDictionary

                jsonDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary

                print(jsonDict)

            }

            catch {

                print(“json error: \(error)”)

            }

        })

        task.resume()

        

    }

    

    

}

You can download the whole source code from here.

Please do share your reviews and comments.

Enjoy Coding 🙂

Advertisements