-1

I am beginner of swift, I had a thread when I parse json data, the object result is nil, can anyone help me to figure out what the problem is. if the func return void, I can get the correct data, but I can not return it as a array. thanks

struct catalogobject: Hashable, Decodable, Encodable{
    let objects: [CatalogObject]?
}

func getCatalog() -> [CatalogObject] {
    var object : [CatalogObject]!
     let url = URL(string: "https://connect.squareupsandbox.com/v2/catalog/list")!
     var request = URLRequest(url: url)
            request.httpMethod = "GET"
            request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
            request.addValue("\(content_type)", forHTTPHeaderField: "Content-Type")
            request.addValue("\(square_version)", forHTTPHeaderField: "Square-Version")
    URLSession.shared.dataTask(with: request) { data, res, error in
        let data = data!
        do {            
            let catalogdata =  try JSONDecoder().decode(catalogobject.self, from: data)
            object = catalogdata.objects
            print("object \(object)")
        }catch{
            print(error)
        }        
      }.resume()
    return object
}
Leo
  • 1

1 Answers1

1

The network request is an async task and you should return your data using the completion block, not this way you return the object. In your code, the function body executed and return before the network call finished its task.

Sample guidance on how you should do:

func getCatalog(_ completion: @escaping ([CatalogObject]) -> ()) {
      let url = URL(string: "https://connect.squareupsandbox.com/v2/catalog/list")!
     var request = URLRequest(url: url)
            request.httpMethod = "GET"
            request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
            request.addValue("\(content_type)", forHTTPHeaderField: "Content-Type")
            request.addValue("\(square_version)", forHTTPHeaderField: "Square-Version")
    URLSession.shared.dataTask(with: request) { data, res, error in
        let data = data!
        do {            
            let catalogdata =  try JSONDecoder().decode(catalogobject.self, from: data)
            completion(catalogdata.objects)
            print("object \(object)")
        }catch{
            print(error)
        }        
      }.resume()
}
Mac3n
  • 4,189
  • 3
  • 16
  • 29