8

This seemingly simple issue is driving me crazy... I am playing around with SwiftyJSON to grab remote data and here is a snippet from my ViewController class in Swift:

override func viewDidLoad() {
    super.viewDidLoad()

    self.statusLabel.text = "welcome"

    RemoteDataManager.getStatusUpdateFromURL { (statusData) -> Void in
        let json = JSON(data: statusData)
        self.statusLabel.text = "this does not work"
        self.statusLabel.text = self.getMostRecentStatusUpdate(json) // also does not work
    }

}

The statusLabel text is set to "welcome" but does not change afterwards. Funny though, anything I put inside func getMostRecentStatusUpdate(_:) with println() is printed to the console correctly, even if it comes from the remote json source (i.e. I know that this function works). My problem is that I cannot get the text printed to a UILabel instead of the console. I do not get any error messages.

I am not yet really familiar with the sort of Swift function like MyClass.myMethod { (myData) -> Void in .... } and I don't understand what's going wrong here. Any ideas?

Pieter
  • 2,621
  • 4
  • 19
  • 26
  • I see... the question is indeed the same. My problem was that Google did not lead me to the answers, most answers were simply about how to update a text label. But it can be deleted, if you prefer. – Pieter Jan 08 '15 at 18:18

1 Answers1

24

UIKit is not thread safe and should only be updated from the main thread. Downloads are done on background thread, and you cannot update UI from there. Try:

override func viewDidLoad() {
    super.viewDidLoad()

    self.statusLabel.text = "welcome"

    RemoteDataManager.getStatusUpdateFromURL { (statusData) -> Void in
        let json = JSON(data: statusData)

        dispatch_async(dispatch_get_main_queue()) {
            self.statusLabel.text = "this does not work"
            self.statusLabel.text = self.getMostRecentStatusUpdate(json) // also does not work
        }
    }
}
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • Fantastic, works like a charm! And I learned something new... thanks! – Pieter Jan 08 '15 at 13:49
  • 7
    With Swift 3, use DispatchQueue.main.async instead of dispatch_async(dispatch_get_main_queue()) – Peter Jun 16 '17 at 02:44
  • @Peter, even i got the same problem, but my code is bit different. I am assigning a static text to a label , but it is displaying some other text. " I removed the label from storyboard and added new label in the same place, connected to old outlet." It worked in my case – Arshad Shaik Dec 06 '18 at 07:28