我试图从本地服务器获取一些数据,使用一段代码在Xcode playground文件中工作:
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
friend_ids = (jsonObj!.value(forKey: "friends") as? NSArray)!
}
}).resume()
return friend_ids
在阅读了关于这个主题的类似问题之后,我知道URLSession是异步运行的,这样函数在从服务器获取任何数据之前返回一个nil值。我还认为我理解完成处理程序可用于确保在继续之前实际获得数据,但遗憾的是我实际上无法理解如何实现数据。有人能够告诉我如何在这个简单的例子中使用完成处理程序,以确保在返回变量之前从服务器获取?
谢谢!
如果你有一个本身正在进行异步工作的函数,它就不能有一个表示异步工作结果的返回值(因为函数返回是立即的)。因此,执行异步工作的函数必须将闭包作为接受预期结果的参数,并在异步工作完成时调用。所以,就你的代码而言:
func getFriendIds(completion: @escaping (NSArray) -> ()) {
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
friend_ids = (jsonObj!.value(forKey: "friends") as? NSArray)!
completion(friend_ids) // Here's where we call the completion handler with the result once we have it
}
}).resume()
}
//USAGE:
getFriendIds(completion:{
array in
print(array) // Or do something else with the result
})