2

I'm sending some POST request to my sever with swift, the usual:

let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            println("error=\(error)")
            return
        }

        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)

        println(responseString) //this is fast
        label.text = "\(responseString)" // this is very slow
}
task.resume()

This works well, I get the data and all. Now there are 2 things that behave very differently and I can't figure out why.

The line: println(responseString) print the data instantly as expected, however, the line label.text = "\(responseString)" takes about 10 seconds to update the label's text.

Any ideas why? has DrawRect got anything to do with this?

matt
  • 2,312
  • 5
  • 34
  • 57

1 Answers1

8

Try doing it on the main thread like this:

dispatch_async(dispatch_get_main_queue(), { () -> Void in
        label.text = "\(responseString)"
    })
Andreas Du Rietz
  • 1,151
  • 11
  • 16
  • 2
    No problem! Whenever you do computations, network requests etc on a background thread then update the UI, always do it on the main thread like this. – Andreas Du Rietz Feb 06 '15 at 15:51