How To Parse JSON Data In iOS (Swift 3 + Xcode 8) ?

JSON Data Parsing In iOS

Hi, In this post, I'll show you how to fetch and parse JSON data from an URL in your iOS app. First, what is JSON?? JSON stands for "JavaScript Object Notation". JSON is the most popular and light weight format for data-interchange. 

In this app, we’ll use http://fixer.io website's API to get the latest currency exchange rates and use them in our iOS app. 

So, let’s start and see how to parse JSON data in iOS.

First of all, open your Xcode and create a Single View Application. 
Give some name to your project and make sure to choose Swift as the language. Click Next.





For this post, we don’t need to work in Storyboard. So just open your ViewController.swift file and write following lines of code in your viewDidLoad() method:



    override func viewDidLoad() {

        super.viewDidLoad()

        
        //Give your api url here
        let url = URL(string: "http://api.fixer.io/latest")
        
        //create your data task here
        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil {
                print("Error!")
            }
            else {
                if let myData = data {
                    do {
                        //creating our json object
                        let myJson = try JSONSerialization.jsonObject(with: myData, options: .mutableContainers) as AnyObject
                        
                        print(myJson)
                    }
                    catch{
                        // catch any error here
                    }
                }
            }
        }
        task.resume()
    }


Now, most important thing, don’t forget to allow arbitrary loads in your App Transport Security Settings from info.plist. But why?? This is because we’re using a http and not a https connection in our api url http://api.fixer.io/latest . So to allow this, we need to follow these steps:
  • Go To Info.plist
  • Click on + sign here

  • Enter App Transport Security Settings

  • Click on arrow sign and then + sign
  • Now, write Allow Arbitrary Loads and change its value from NO to YES

That’s it. After following above steps, just run your app and you’ll get following output in your console:




So now, we've our JSON data in console and we can now use this data as per our requirements. Assume, we want to get to some specific currency rate from this JSON data. So to do this, just go further into the dictionary and pick that specific currency by adding following lines in your code(example):

            //getting into our json data
    if let rates = myJson ["rates"] as? NSDictionary
            {
               if let myCurrency = rates["INR"]
                   {
                     //printing the value in our console
                     print(myCurrency)
                    }
             }


So now, when you run this app, it will give you the rate only of the currency that you have written in your code i.e. INR. 

This is how you can go further and extract your JSON data as per your own requirements.

Here’s the full code for your reference:


That's all about parsing JSON data in iOS. You can now parse any kind of api data using the same approach. I hope this post may help someone, somehow!

If you've any doubts or need any further help, then do message me in the comments section below and I'll try to respond you as soon as possible.

Thanks for your time. Keep coding.. 👨‍💻

Comments

Popular posts from this blog

PayPal Integration In iOS Applications | Payment Gateways iOS/Swift

MacBook Magic: Exploring the Enchanting World of Apple's Laptops

Convert Swift Code To Kotlin Using SwiftKotlin Mac Tool