本文介绍了NSURLSession完成处理程序非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
运行以下代码时,几乎可以立即打印响应,但是,它可能需要十秒钟或更长时间才能显示在视图中.似乎最类似的问题是由会话和处理程序位于不同的线程上引起的.但是为什么最终会起作用呢?很困惑...
When I run the following code, I can print a response almost immediately, however, it can take ten seconds or more to appear in my view. It seems like most similar problems are caused by the session and the handler being on different threads. But why does it work eventually? Very confused...
func downloadDetails(completed: DownloadComplete) {
let url = NSURL(string: _detailsURL)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in
do {
let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
if let eyeColor = dict["eyeColor"] as? String {
self._eyeColor = eyeColor
}
}
catch {
print("json error: \(error)")
}
}
task.resume()
}
推荐答案
您需要将UI更新发送到主队列,如果尝试在不将其发送到主队列的情况下进行更新,则可能需要一分钟的时间才能更新它.
You need to send your UI updates to the main queue, If you try to update it without sending it to the main queue it can take over a minute to update it.
func downloadDetails(completed: DownloadComplete) {
let url = NSURL(string: _detailsURL)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in
do {
let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
if let eyeColor = dict["eyeColor"] as? String {
dispatch_async(dispatch_get_main_queue()) {
self._eyeColor = eyeColor
}
}
}
catch {
print("json error: \(error)")
}
}
task.resume()
}
这篇关于NSURLSession完成处理程序非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!