你的UI佈局的更新(標籤文本的變化,框架修改..)必須是主線程,在你的代碼進行網絡通話,它在後臺線程可能推出:
let url = NSURL(string: "http://catfacts-api.appspot.com/api/facts")
let request = NSURLRequest(URL: url!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler : { data, response, error in
if let feed = (try? NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)) as! NSDictionary! {
if let catFactArray = feed.valueForKeyPath("facts") as! NSArray! {
if !NSThread.isMainThread {
print("Yes , I'm not in the main thread..")
}
dispatch_async(dispatch_get_main_queue(), {
print("Now I'm in the main thread..")
self.catLabel.text = catFactArray[0] as? String
self.view.setNeedsDisplay()
self.catLabel.setNeedsDisplay()
self.catLabel.layoutIfNeeded()
}
}
}
})
task.resume()
嘗試將標籤更新放在側主隊列中。 – Amit89
如果您將代碼作爲文本粘貼到問題中,您就更有可能得到迴應。很難閱讀屏幕截圖,其他用戶無法複製並編輯它們以測試代碼。 –