IOS tag does not update text with function in Swift

This seemingly simple problem drives me crazy ... I play with SwiftyJSON to capture deleted data, and here is a snippet of 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 } } 

In the text statusLabel is set to "welcome", but after that it does not change. It's funny, but everything that I put inside func getMostRecentStatusUpdate(_:) with println() is correctly output to the console, even if it comes from a remote json source (i.e. I know this function works). My problem is that I cannot get the text printed in UILabel instead of the console. I do not receive error messages.

I am still not very familiar with such a Swift function as MyClass.myMethod { (myData) -> Void in .... } , and I do not understand what is happening here. Any ideas?

+6
source share
1 answer

UIKit not thread safe and should only be updated from the main thread. Downloads are performed in the background thread, and you cannot update the interface 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 } } } 
+22
source

Source: https://habr.com/ru/post/980701/


All Articles