Swift:URLSession完成处理程序
我正在尝试使用一段在Xcode文件中工作的代码从本地服务器获取一些数据:Swift:URLSession完成处理程序,swift,completionhandler,urlsession,Swift,Completionhandler,Urlsession,我正在尝试使用一段在Xcode文件中工作的代码从本地服务器获取一些数据: URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? N
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
})
如果您有一个本身正在执行异步工作的函数,那么它不能有一个表示该异步工作结果的返回值,因为函数返回是即时的。因此,执行异步工作的函数必须将闭包作为参数,该参数接受预期结果,并在异步工作完成时调用。因此,对于您的代码:
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
})
我尝试过这个,但它似乎忽略了完成块。如果我逐行遍历,它只会从URLSession行到resume行两次,然后退出函数?您要检索什么URL?请求可能超时或失败。特别是如果URL是http://而不是https://,在这种情况下,除非创建异常,否则它将被iOS应用程序传输安全性阻止。有任何信息打印到控制台吗?我已经尝试过了,但它似乎忽略了完成块。如果我逐行遍历,它只会从URLSession行到resume行两次,然后退出函数?您要检索什么URL?请求可能超时或失败。特别是如果URL是http://而不是https://,在这种情况下,除非创建异常,否则它将被iOS应用程序传输安全性阻止。有任何信息打印到控制台吗?