NSURLSession completion handler very slow

…衆ロ難τιáo~ 提交于 2019-12-12 02:59:29

问题


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()
}

回答1:


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()
}



回答2:


Use :

dispatch_async(dispatch_get_main_queue()) {

/// to load your UI

}




回答3:


For Swift 3 you can use this:

DispatchQueue.main.async() {
   self._eyeColor = eyeColor
}


来源:https://stackoverflow.com/questions/35029692/nsurlsession-completion-handler-very-slow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!