Swift:URLSession完成处理程序

时间:2017-12-29 01:06:52

标签: swift completionhandler 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

在阅读了有关此主题的类似问题之后,我知道URLSession是异步运行的,因此函数在从服务器获取任何数据之前返回nil值。我还认为我理解完成处理程序可用于确保在继续之前实际获得数据,但遗憾的是我实际上无法理解如何实现数据。有人可以告诉我如何在这个简单的例子中使用完成处理程序,以确保在返回变量之前从服务器获取?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果你有一个本身正在进行异步工作的函数,它就不能有一个表示异步工作结果的返回值(因为函数返回是立即的)。因此,执行异步工作的函数必须将闭包作为接受预期结果的参数,并在异步工作完成时调用。所以,就您的代码而言:

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
})
相关问题