Swift 3:不使用iOS中的完成处理程序

时间:2016-10-21 07:10:07

标签: ios iphone swift

我在NSObject类中使用完成处理程序创建了一个函数来使用Web服务。但是我没有办法用处理程序返回来调用该函数。

func getUser(url:String, completionHandler: @escaping (NSDictionary?, NSError?) -> ()) {

    let config = URLSessionConfiguration.default // Session Configuration
    let session = URLSession(configuration: config) // Load configuration into Session
    let url = URL(string: url)!

    let task = session.dataTask(with: url, completionHandler: {
        (data, response, error) in

        if error != nil {
           completionHandler(nil, error as NSError?)
        } else {
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [NSDictionary: Any] {
                    completionHandler(json as NSDictionary?,nil)
                }
            } catch {
                print("error in JSONSerialization")
            }
        }
    })
    task.resume()
}

1 个答案:

答案 0 :(得分:1)

您应该确保在每种情况下都调用completionHandler:例如,当JSONSerialization抛出时,您会抓住并打印错误,但是您没有调用completionHandler 1}}。如果JSON结果为nil

,则相同

<强>添加

你可以这样处理它:

do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [NSDictionary: Any]
    completionHandler(json,nil)
} catch(let error) {
    print(error)
    completionHandler(nil, error)
}