我在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()
}
答案 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)
}