Search code examples
iosswiftuilabelclosures

How to change content of UILabel inside of a closure


I can't change content of UILabel inside of a closure. I googled, yet solution is nowhere to be found.

Here is related piece of my code:

class ViewController: UIViewController {

    @IBOutlet var city: UITextField!
    @IBOutlet var message: UILabel!
    @IBAction func buttonPressed(sender: AnyObject) {

        var urlString = "http://google.com"
        var url = NSURL(string: urlString)


        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!) {(data, response, error) in

            self.message.text = "try"
            println("done")
        }

        task.resume()
    }
    ... //rest of the code

It should change contents of UILabel message with "try" when I click the button. It prints out "done" in the console, but it does not change content of UILabel.


Solution

  • You can change it by using dispatch_async on main thread. UI updates have to be done in the main thread. dataTaskWithURL executes in a background thread.

    let task = session.dataTaskWithURL(url!) {(data, response, error) in
    
        if (error == nil)
        {
           dispatch_async(dispatch_get_main_queue(),
           {
              self.label.text = "Updated"
           })
        }
    }