Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView.init() must be used from main thread only (when i segue to this controller)

Tags:

ios

swift

Hello this is my controller class

 class  passwordViewController: UIViewController {

 let load = UIActivityIndicatorView(style: .whiteLarge) // cause error

 let passwordTextFiled:UITextField = { // cause error

            let pass = UITextField()
            pass.placeholder = ""
            pass.addDoneButtonOnKeyboard()
            pass.textColor = .gray
            pass.textAlignment = NSTextAlignment.center
            return pass
        }()

        let barLabel:UILabel = {
            let bar = UILabel()
            bar.text=""
            bar.backgroundColor = Colors.yellow
            return bar
        }()
         // there is more code here.i avoid to copy
}

when i run this controller directly it is okay no error. but when i segue from other controller here cause this error

UIView.init() must be used from main thread only

update 1 :

there is A controller with one button and the button segue to controller B

and this is my segue code :

 DispatchQueue.main.async {

            self.performSegue(withIdentifier: "passVC", sender: nil)

           }

and i have B controller's code here swift 4 and code 10

like image 564
Ryan110 Avatar asked Dec 23 '22 02:12

Ryan110


2 Answers

The error is telling you that you are creating the view controller from a background thread and that it must be created on the main thread (All UI work must be done on the main thread).

So when you are in the background thread and want to do UI work, you should use a dispatch queue call to run the code in the correct thread.

DispatchQueue.main.async {
   // UI work here
}

So in your case, I imagine you are doing some network request to check authentication.

networkService.checkAuth() { auth in 
     // do whatever NON UI work you need to here
     DispatchQueue.main.async {
         // UI work here
     }
} 
like image 183
Scriptable Avatar answered Dec 29 '22 11:12

Scriptable


  DispatchQueue.main.async { 
       //do UIWork here 
}
like image 22
Radhe Yadav Avatar answered Dec 29 '22 10:12

Radhe Yadav