jas*_*og 2 completionhandler swift urlsession
我正在尝试使用在 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
Run Code Online (Sandbox Code Playgroud)
在阅读了有关此主题的一些类似问题后,我知道 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
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5514 次 |
| 最近记录: |