我有一个执行HTTP请求并从网站检索数据的方法,它按预期工作,我正确获取了数据。我没办法做的就是在调用该方法时返回检索到的值。
这是代码...
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"
,因为在返回调用之前myData
内的let task =
变量已被修改。我尝试在let task =
内部返回,但这无法在Swift中完成。
调用myFunction
时如何返回检索到的值?
答案 0 :(得分:1)
您需要完成,因为请求是异步的
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)
}
}