我试图从网络呼叫中获取并返回一些(json)数据,并且我想知道是否有更好的方法来等待网络数据而不仅仅是空循环。< / p>
这是我的代码:
MyLibrary.bib
我记得在Objective-C中尝试类似的东西,导致在运行时出现无限循环。
答案 0 :(得分:3)
如果要从异步操作返回值,则需要完成处理程序。 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
}