みかづきブログ その3

本ブログは更新を終了しました。通算140万ユーザーの方に観覧頂くことができました。長い間、ありがとうございました。

👆

引越し先はこちらです!

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. に負けずにSwiftでHTTPリクエストしてUITextViewのテキストを差し替える

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.

という感じでエラーを吐くことになるでしょう。