简体   繁体   中英

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.

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

You need to perform UI changes on the main thread in order to make it faster, Because i think http requests are made asynchronously for example downloading an image. So in your code you can do as follows

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM