23

JSON Parsing iOS Tutorial

 5 years ago
source link: https://www.tuicool.com/articles/hit/AZZfUnr
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

jUVfiu6.png!web

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.

YNRreu6.png!web

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

2EfUB3i.png!web

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.

eueim2i.png!web

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

r6fAF3n.png!web

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 Runthe project, the date and time values are written to the screen.

ANzmyaf.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK