我在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()
}发布于 2016-10-21 07:15:37
您应该确保在每种情况下都调用您的completionHandler:例如,当JSONSerialization抛出时,您捕获并打印错误,但您没有调用您的completionHandler。如果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)
}https://stackoverflow.com/questions/40170440
复制相似问题