Simplified iOS

  • Home
  • About
  • Contact
  • Advertise
  • Write for Us

Swift JSON Tutorial – Fetching and Parsing JSON from URL

February 8, 2017 by Belal Khan 7 Comments

In this Swift JSON Tutorial we will learn about fetching and parsing JSON from a URL. You may already know what is JSON file. JSON stands for “JavaScript Object Notation” it is the most popular data interchange format. In our iOS Application we can use this to fetch data from an external MySQL Database. I have already posted a tutorial about Xcode JSON Example.

Update: Learn JSON Parsing using Swift 4.

So lets start this Swift JSON Tutorial.

Swift JSON Tutorial

The JSON File

  • I already have my JSON file in my local xampp server. The file is as below.

swift json tutorial

  • This is a very simple JSON file. As today we will learn only to fetch and display the names in our iOS Application. And in the next tutorial we will make the JSON filled with a little more data and we will learn creating a list with it.

Xcode Project

  • So lets create a new Xcode Project. I am using Xcode 8.
  • Again create a Single View Application, I have created SwiftJSONTutorial.
  • In Main.storyboard drag a Label. And set Lines property of the Label to 0. Also Change the Width and Height of the Label so that it can easily hold all the names of the JSON.

swift json tutorial

 

  • Also connect your Label to ViewController.swift, if you don’t know how to do this please go through the Xcode Button Tutorial, where I already explained about connecting a View to Code.
  • Now come inside ViewController.swift and write the following code.

ViewController.swift

  • Modify your ViewController.swift as below.
//
//  ViewController.swift
//  SwiftJSONTutorial
//
//  Created by Belal Khan on 08/02/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    //the json file url
    let URL_HEROES = "http://192.168.1.105/json/heroes.php";
    
    //A string array to save all the names
    var nameArray = [String]()

    //the label we create
    @IBOutlet weak var labelTest: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //calling the function that will fetch the json
        getJsonFromUrl();
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //this function is fetching the json from URL
    func getJsonFromUrl(){
        //creating a NSURL
        let url = NSURL(string: URL_HEROES)
        
        //fetching the data from the url
        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
            
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
               
                //printing the json in console
                print(jsonObj!.value(forKey: "avengers")!)
                
                //getting the avengers tag array from json and converting it to NSArray
                if let heroeArray = jsonObj!.value(forKey: "avengers") as? NSArray {
                    //looping through all the elements
                    for heroe in heroeArray{
                        
                        //converting the element to a dictionary
                        if let heroeDict = heroe as? NSDictionary {
                            
                            //getting the name from the dictionary
                            if let name = heroeDict.value(forKey: "name") {
                                
                                //adding the name to the array
                                self.nameArray.append((name as? String)!)
                            }
                            
                        }
                    }
                }
                
                OperationQueue.main.addOperation({
                    //calling another function after fetching the json 
                    //it will show the names to label
                    self.showNames()
                })
            }
        }).resume()
    }
    
    func showNames(){
        //looing through all the elements of the array
        for name in nameArray{
            
            //appending the names to label
            labelTest.text = labelTest.text! + name + "\n";
        }
    }


}
  • Coding part is over the only thing we need to allow the http connection in the Info.plist file.

Modifying NSAppTransportSecurity

  • Now click on Info.plist. And change it as shown in the image.

swift json tutorial xcode

  •  As you can see I have added App Transport Security Settings. You can do it by clicking on the plus icon. And inside it you have to set Allow Arbitrary Loads as YES.
  • Now thats it you can launch your application in Simulator.

swift json example

  • Bingo! Its working absolutely fine. If you are having problems you can get the source code of this Swift JSON Tutorial from below.

[sociallocker] Swift JSON Tutorial (1115 downloads) [/sociallocker]

So thats all for this Swift JSON Tutorial. In the next post we will make the JSON a little more filled with data and then we will see building a Custom Table View with Texts and Images.

And if you are having any problems or confusions regarding this Swift JSON Tutorial, don’t hesitate to leave your comments below. Thank You 🙂

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Development Tutorial, Swift Tagged With: json parsing, swift json, swift json tutorial

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, iphone etc.

Comments

  1. Varsha Chauhan says

    February 11, 2017 at 3:18 pm

    Hello sir…
    I am making an android application in which i have completed the login and registration part using PHP and wamp server. Now i am stuck at point where i want that the logged in user should see the headings of the data in listview stored in database and when the user click on any of the item the next activity should open displaying full details of the heading. Also i want to filter the listview items on the basis of multiple conditions like in E-Commerce applications we can filter on the basis of brands,price,colour etc simultaneoulsy. I want that the listview items should be fetched from the database.
    One more thing i want that the details of the item should contain a a hyperlink named “download” so that the image can be downloaded in the phone.
    I want guidance on how to achieve them.
    Please reply .

    Reply
    • dt says

      September 17, 2017 at 7:56 am

      This is iOS (iPhone) NOT ANDROID so it won’t work. Sorry.

      Reply
      • Ryan says

        October 20, 2017 at 1:40 am

        Will this work with AppleTV? I tried and debugged the URLsession and get a response but no data…

        Response
        Optional(HTTP/1.1 200 no error
        Cache-Control: max-age=0, private, must-revalidate
        Date: Fri, 20 Oct 2017 01:11:45 GMT
        Content-Length: 0
        Etag: W/”ad6542ff332466594ef909dd3d2f4153″
        X-Request-Id: a7061f7d-f0a9-4468-8ba3-d63b1488f75d
        X-Frame-Options: SAMEORIGIN
        Content-Type: application/json; charset=utf-8
        Connection: keep-alive
        X-Content-Type-Options: nosniff
        X-Xss-Protection: 1; mode=block
        Transfer-Encoding: Identity
        Via: 1.1 vegur
        X-Runtime: 1.316226
        Server: Cowboy)
        data
        Optional(4379 bytes)
        json
        nil

        The code is…
        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
        print (“Response”)
        print (response)
        print (“data”)
        print (data)
        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
        print (“json”)
        print (jsonObj)

        any thoughts?

        Reply
  2. savita dayma says

    November 13, 2017 at 7:52 am

    thank u sir… its really helpful for me

    Reply
  3. David Collins says

    November 15, 2017 at 3:19 am

    Thanks, Belal. Very clear and concise.

    Reply
  4. valjo says

    March 31, 2018 at 2:17 pm

    Hey Thanks for this amazing Tut.

    Can you update the code with the new function of JSONDecoder().decode in Swift 4?

    Would be a lot easier to see through.

    Reply
  5. Vivek Panchal says

    May 4, 2018 at 11:04 am

    How to Work with this type of JSON Data

    {
    “1”: {
    “Name”: “Afghanistan”,
    “Rate”: 0.435,
    “PhoneNo”: “93”
    },
    “2”: {
    “Name”: “Afghanistan”,
    “Rate”: 0.6225,
    “PhoneNo”: “9370, 9372, 9375, 9376, 9377, 9378, 9379”
    },
    “3”: {
    “Name”: “Albania”,
    “Rate”: 0.2775,
    “PhoneNo”: “35543, 355422, 355423, 355424”
    },
    “4”: {
    “Name”: “Albania”,
    “Rate”: 0.3825,
    “PhoneNo”: “3553, 3555, 3558, 35521, 35522, 35524, 35526, 35527, 35528, 35529, 35546, 35547, 35548, 35549, 35572”
    }
    }

    Reply

Leave a Reply Cancel reply

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




About Me

belal khan simplified ios

Hello I am Belal Khan, founder and owner of Simplified iOS. I am currently pursuing MCA from St. Xavier's College, Ranchi. Apart from my academic I am a blogger, I run various websites and majority of them are about coding and development.

Connect with Me

Follow Simplified iOS

Simplified iOS

Popular Posts

  • Swift SQLite Tutorial for Beginners – Using… (99,380)
  • Swift PHP MySQL Tutorial – Connecting iOS App… (98,248)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (79,974)
  • Download Full High Sierra Installer to Create Bootable USB (70,273)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (67,256)
  • How to Format USB on Mac? Formatting External Hard… (61,373)
  • Swift JSON Tutorial – Fetching and Parsing… (59,402)
  • Firebase Realtime Database Tutorial for Swift using Xcode (53,697)
  • iOS Registration Form Example using PHP and MySQL (48,915)
  • Xcode Text Field Tutorial for iOS Application using Swift (41,145)




About

Simplified iOS is a blog where you can find latest tutorials related to coding and app development for iphone and MAC OS. Here you can get Simplified iPhone, iPad and Mac OS development tutorial to know the things about Apple Development from basics to advanced level.

Quick Links

  • Advertise
  • Contact
  • Disclaimer
  • Privacy Policy
  • Write for Us

Copyright © 2017 · Simplified iOS· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·