Search code examples
iosjsonswiftdictionaryget

assigning "Get" Request data to Text field


My get data response is like

I want "title" and "date" should be shown in my view controller "label values"

get method calls when app running and the data should display in either text fields "or" in label

My Code is

guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { fatalError() }

let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
    if let response = response {
        print(response)
    }

    if let data = data {
        print(data)
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            print(json)
        } catch {
            print(error)
        }

    }
}.resume()

out put is :

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "[email protected]",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
]

I want to print "username": "email": values in my Storyboard labels


Solution

  • The result contains multiple users, so you should first iterate over them and find the user you want. Then you can set text on your UI elements in the Main thread.

    guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { fatalError() }
    
    typealias User = [String: Any]
    
    let session = URLSession.shared
    session.dataTask(with: url) { (data, response, error) in
        if let response = response {
            print(response)
        }
    
        if let data = data {
            print(data)
            do {
                let usersJson = try JSONSerialization.jsonObject(with: data, options: []) as! [User]
                print(usersJson)
    
                // Since the result is an array of users
                for user in usersJson {
                    guard let userName = user["username"] as? String else { return assertionFailure("Invalid username") }
                    print(userName)
    
                    // All UI works should done in main thread
                    DispatchQueue.main.async {
                        <#usernameLabel#>.text = username
                    }
                }            
            } catch {
                print(error)
            }
    
        }
    }.resume()
    

    I suggest you take a look at Swift Codable. It will boost your coding and minimize syntax and human errors.