jsonswiftxcodeget-requestgetresponse

Loop Json Links Swift


I've got an array with two links where I want to get the value of id. The code works but the device_id_array varies between [88.0, 89.0] and [89.0, 88.0] and I don't know how to fix this. Thanks for your help.

 override func viewDidLoad() {
    super.viewDidLoad()


    device_link_array = ["http://link1.com", "http://link2.com"]

    for link in device_link_array {
        let url = URL(string: link)


        let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            if error != nil
            {
                print("Error")

            }else{

                if let content = data{
                    do{     

                        let json = try JSONSerialization.jsonObject(with: content, options: []) as! [String:Any]

                        if let device_id = json["id"]{
                            device_id_array.append(device_id as! Double)
                        }
                        print(device_id_array)

                    }catch{}
                }
            }
        }
        task.resume()
    }
}

Json Link1 : { "id": 88 }

Json Link2 : { "id": 89 }

UPDATE:

    device_link_array = ["http://link1.com", "http://link2.com"]

    let group = DispatchGroup()
    for links in device_link_array {
        let url = URL(string: links)

        group.enter()
        let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            if error != nil
            {
                print("Error")
            }
            else{

                if let content = data{
                    do{

                        let json = try JSONSerialization.jsonObject(with: content, options: []) as! [String:Any]
                        if let device_id = json["id"]{
                            device_id_array.append(device_id as! Double)

                        }
                        print(device_id_array)

                    }catch{}
                }
            }
            group.leave()
        }

        task.resume()

    }
}

Solution

  • You should use an array of Device object defined by:

    class Device {
        var link: String
        var identifier: Double?
    
        init(link: String) {
            self.link = link
        }
    }
    
    let deviceArray: [Device] = [
            Device(link: "http://link1.com"),
            Device(link: "http://link2.com")]
    

    Then you change you loop to:

    for device in deviceArray {
         let link = device.link
         ... // URLSession stuff
                    if let deviceId = json["id"]{
                            device.identifer = deviceId as! Double
                    }
                    print(deviceArray)
         ...
    

    You will be able to access to your first identifer with:

    if let firstIdentifier = deviceArray[0].identifier {
        print(firstIdentifier)
    }