Refresh ui textbox in swift ios

I am answering the question when I use the fast ios SDK 8

I have used a callback to fetch the background of the data and when fetching the data, I want to set the value of the textbox and refresh window.

here is my code:

@IBOutlet var txtTest: UITextField!

@IBAction func login() {
    let username = "aaa";
    let password = "bbb";
    var res = ServiceClient.login(username, password: password){
        (res:String, error:String?) -> Void in if(error == nil){
            self.txtTest.text = res;
        }
    }
}

      

Run this code and the data is selected correctly and the txtTest is not updated, but when I hit txtTest this value will be shown. So is there a way to force the interface to update? or send a message to the UI thread?

+3


source to share


2 answers


Same problem every user faces when they want to update the UI in Swift: never update the UI in any secondary thread. And that means anything with closure. Because Swift uses so many closures, this problem is seen a lot more, but it's not new.



See Swift Update Label (with HTML content) takes 1 minute for the correct way of doing things.

+6


source


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

For quick 3 and quick 4

DispatchQueue.main.async {
    self.txtTest.text = "Your text"
}

      



Related repetitive question, but with a specific answer

iOS label does not update text with function in Swift

+2


source







All Articles