Zoltan Zoltan - 2 months ago 10
iOS Question

After HTTP POST request UIView change delays

I have use this code to make HTTP POST request:

let myURL = NSURL(string: serverURL)

let request = NSMutableURLRequest(URL: myURL!)

request.HTTPMethod = "POST"

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
print(error)
} else {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(responseString)
self.view.backgroundColor = UIColor.redColor()
}

}

task.resume()


I have experience that the view's
backgroundColor
changes after several seconds from the print of the responseString.

Why is that and how can I make it simultaniously?

Thanks.

Answer

Always perform UI changes on main thread, so change your view's backgrondColor on the main thread like this way.

dispatch_async(dispatch_get_main_queue(),{
    self.view.backgroundColor = UIColor.redColor()
}