从 HTTP 请求中检索到 return 值的方法

Method to return value retrieved from HTTP request

我有一个方法可以执行 HTTP 请求并从网站检索数据,它按预期工作,我正在正确获取数据。我没能做到的是 return 调用方法时检索到的值。

这是代码...

func myFunction(zipCode: String)->String{
    var myData:String = ""

    let siteLink = "http://example.com/zip/" + zipCode
    let url = URL(string: siteLink)

    let task = URLSession.shared.dataTask(with: url!) { data, response, error in
        guard error == nil else {
            print(error!)
            return
        }
        guard let data = data else {
            print("Data is empty")
            return
        }
        let json = try! JSONSerialization.jsonObject(with: data, options: [])
        guard let jsonArray = json as? [[String: String]] else {
            return
        }
        myData = jsonArray[0]["MyPropertyName"]!
        // Here, myData outputs, "Info for zip code 52484 from HTTP request"
    }

    task.resume()

    return myData
}

当我调用 myFunction 时,我得到一个空字符串...

myFunction(zipCode: "52484")// Outputs an empty string

我期望看到的是 "Info for zip code 52484 from HTTP request" 的 return 值,因为 myData 变量在 return 调用之前在 let task = 中被修改.我在 let task = 中尝试了 returning,但这不能在 Swift 中完成。

如何在调用 myFunction 时 return 检索到的值?

您需要完成,因为请求是异步的

func myFunction(zipCode: String,completion:@escaping(_ str:String?) -> () ) {

    let siteLink = "http://example.com/zip/" + zipCode
    let url = URL(string: siteLink)

    let task = URLSession.shared.dataTask(with: url!) { data, response, error in
        guard error == nil else {
            print(error!)
            completion(nil)
            return
        }
        guard let data = data else {
            print("Data is empty")
            completion(nil)
            return
        }
        let json = try! JSONSerialization.jsonObject(with: data, options: [])
        guard let jsonArray = json as? [[String: String]] else {
            completion(nil)
            return
        }
        let myData = jsonArray[0]["MyPropertyName"]!
        completion(myData) 
    } 
    task.resume() 
}

通话

myFunction(zipCode: "52484") { (str) in 
  if let st = str {
    print(st)
   }
}