[英]Swift 3: not working with completion handler in iOS
I have created one function using completion handler in NSObject class for consumption of web services. 我使用NSObject类中的完成处理程序创建了一个函数,用于消耗Web服务。 However I am not getting a way to call that function with handler return.
但是我没有办法用处理程序返回来调用该函数。
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()
}
You should make sure that your completionHandler
is called in every cases: for example, when the JSONSerialization
throws, you catch and print the error, but you're not calling your completionHandler
. 你应该确保你的
completionHandler
被称为在每个情况:例如,当JSONSerialization
抛出,你赶上和打印错误,但你不打电话给你completionHandler
。 The same if the JSON
result is nil
如果
JSON
结果为nil
ADDING 新增
You can handle it in this way: 您可以通过以下方式进行处理:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [NSDictionary: Any]
completionHandler(json,nil)
} catch(let error) {
print(error)
completionHandler(nil, error)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.