JSON Parsing iOS Tutorial

JSON (JavaScript Object Notation) is a lightweight format, which is widely used to send data over the internet. The JSON format includes dictionaries and arrays. In this tutorial some data is requested from a web server and displayed on screen. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSJSONTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard. Add 4 Labels to the Storyboard. Position and name the Labels according to the following screenshot.

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl + drag from the right date Label to the ViewController class and create the following Outlet.

Ctrl + drag from the right Time Label to the ViewController class and create the following Outlet.

JSONTest.com is a testing platform for services utilizing JavaScript Object Notation (JSON). In this case we make use of the date service. This will return the current date and time.

Create a struct which will hold the date and time values retreived from the JSON object.

struct JSONTest: Codable {
    let date: String
    let time: String
}

Change the viewDidLoad method in.

 override func viewDidLoad() {
    super.viewDidLoad()

    // 1
    let urlString = "http://date.jsontest.com"
    guard let url = URL(string: urlString) else { return }
    
    // 2
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if error != nil {
            print(error!.localizedDescription)
        }

        guard let data = data else { return }
        do {
            // 3
            //Decode data
            let JSONData = try JSONDecoder().decode(JSONTest.self, from: data)

            // 4
            //Get back to the main queue
            DispatchQueue.main.async {
                self.dateLabel.text = JSONData.date
                self.timeLabel.text = JSONData.time
            }

        } catch let jsonError {
            print(jsonError)
        }
        // 5
        }.resume()
}
  1. an URL object containis the url of the web service.

  2. The dataTask(with:completionHandler:) method creates a task that retrieves the contents of at the URL

  3. The decode(_:from:) method will perform the decoding of the JSON object

  4. The date and time values from the JSON object are assigned to the labels

  5. The resume method begins the web request.

Build and Run the project, the date and time values are written to the screen.

You can download the source code of the IOSJSONTutorial at the ioscreator repository on Github