swiftxcodeswift5jsonparseriosdeployment

How to store data in array from web api


I am using Xcode 11.3.1, Swift 5 and trying to show data in table view through web api. So after fetching the data I want to store "name" data in countryList. countryList is an array.

URLSession.shared.dataTask(with: url!) { (data, response, error) in

        do
        {if error == nil{

            let parsedData = try JSONSerialization.jsonObject(with: data!) as? NSDictionary
            let tableData = parsedData?["data"] as! NSArray

            self.countryList = [tableData.value(forKey: "name") as? String]
            print("DEVELOPER: \(self.countryList)")

            DispatchQueue.main.async {
                self.countryTable.reloadData()
            }
            }
        }
        catch{
            print(error.localizedDescription)
        }

    }.resume()

//Web Api

{ "status": 200, "data": [ { "name": "Afghanistan", "id": 1 }, { "name": "Albania", "id": 2 }, { "name": "Algeria", "id": 3 }, { "name": "American Samoa", "id": 4 } ], "message": "List of all countries." }


Solution

  • Try

    guard let data = data else { return }
    let parsedData = try JSONSerialization.jsonObject(with: data) as! [String:Any]
    let tableData = parsedData["data"] as! [[String:Any]] 
    self.countryList = tableData.compactMap {  $0["name"] as? String }
    

    Recommenced

    do { 
       let res = try JSONDecoer().decode(Root.self,from:data)
        print(res.data)
     }
    catch {
       print(error)
     }
    

    struct Root : Codable {
       let status:Int
       let data:[Model]
    }
    
    struct Model:Codable {
      let name:String
      let id:Int
    }