NSURLSession完成处理程序非常慢

时间:2016-01-27 05:43:40

标签: ios swift2 nsurlsession completionhandler

当我运行以下代码时,我几乎可以立即打印响应,但是,在我的视图中可能需要十秒或更长时间。似乎大多数类似的问题是由会话和处理程序在不同的线程上引起的。但为什么它最终会起作用?很困惑......

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

3 个答案:

答案 0 :(得分:1)

使用:

dispatch_async(dispatch_get_main_queue()) {

///加载您的用户界面

}

答案 1 :(得分:1)

您需要将UI更新发送到主队列,如果您尝试更新它而不将其发送到主队列,则可能需要一分钟才能更新它。

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 :(得分:0)

对于Swift 3,你可以使用它:

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