我正在尝试从网络调用中获取和返回一些 (json) 数据,我想知道是否有比空循环更好的等待网络数据的方法。
这是我的代码:
func sendAPIRequest(endpoint:String) -> JSON?
{
var json = JSON("")
let request = NSMutableURLRequest(URL: NSURL(string: "https://host.com/".stringByAppendingString(endpoint))!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
}
json = JSON(data: data!)
}
task.resume()
while (json == "") {
// Wait
}
return json
}
我记得在 Objective-C 中尝试过类似的东西,结果在运行时导致了无限循环。
最佳答案
如果你想从异步操作中返回值,你需要一个完成处理器。 dataTaskWithRequest
是一个异步进程。这样做:
func sendAPIRequest(endpoint:String, complete: (JSON) -> ())
{
var json = JSON("")
let request = NSMutableURLRequest(URL: NSURL(string: "https://host.com/".stringByAppendingString(endpoint))!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
json = JSON(data: data!)
complete(json)
}
}
task.resume()
}
然后像这样调用它:
sendAPIRequest(<your endpoint string>) { theJSON in
//Use the Json value how u want
}
关于ios - 在返回值之前等待网络调用完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38665139/