Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode 9 update Swift, purple warning

Not sure why after updating to Xcode 9 my project (originally created in Swift 3) is showing purple warnings: UITextField.text must be used from main thread only

I'm only checking in If statement if text field is empty... attaching screenshot.

enter image description here

like image 808
KirillC Avatar asked Nov 28 '22 08:11

KirillC


1 Answers

The login manager is running your closure on a thread other than the main thread and you can't use user interface elements off the main thread.

Others have said that it's OK just to read UI properties on side threads and they are probably right, but there is no absolute guarantee of it and, personally, I would heed the warnings. For example, accessing those properties could have side effects. Perhaps their values are cached somewhere and the main thread is in the process of updating or deleting the property just when you want to access it.

The proper way to silence the warnings is to execute your cloasure on the main thread e.g.

LoginManager.checkLoginStatus {
    isLoggedIn in

    DispatchQueue.main.async {

        // Do all your UI stuff here

    }
 }

This way the thread that runs the closure does nothing except schedules the code to run in the main queue which always runs on the main thread.

like image 89
JeremyP Avatar answered Dec 14 '22 03:12

JeremyP