HTTPリクエストでスコアをゲットしようとした場合です。
Swift
let URL = NSURL(string: "{URL}") let request = NSMutableURLRequest(URL: URL!) request.HTTPMethod = "GET" let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { data, response, error in if (error == nil) { do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary let score = json["score"] as! String print(score) } catch { } } else { } }) task.resume()
ゲットした値をプリントするのであればこれでOKです。
しかし、リクエストの結果をViewに適用する処理をバックグラウンドの中に書きたいのであれば、
let URL = NSURL(string: "{URL}") let request = NSMutableURLRequest(URL: URL!) request.HTTPMethod = "GET" let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { data, response, error in if (error == nil) { do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary let score = json["score"] as! String dispatch_async(dispatch_get_main_queue(), { self.textView.text = score }) } catch { } } else { } })
という感じで、
dispatch_async(dispatch_get_main_queue(), {
// ここだ!
})
の中に記述しましょう。
さもなくば、
This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.
という感じでエラーを吐くことになるでしょう。