Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 / Xcode 8.2 - switch view in viewDidLoad not working

I want to switch the ViewController on load when the user is already logged in. The problem: The view didnt change when user is equal to "true"...

Thank you in advance!!

override func viewDidLoad() {
    super.viewDidLoad()

    var user: String?
    user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String

    if user == "true" {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
        self.show(vc!, sender: vc)
    }

    // Do any additional setup after loading the view, typically from a nib.
}
like image 988
KMax Avatar asked Feb 05 '23 11:02

KMax


2 Answers

Remove the code from viewDidLoad method and use the below method.

 override func viewDidAppear() {
     guard let user = UserDefaults.standard.string(forKey: "loginSuccessfull"), user == "true" else {
      return
     }
     let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView")!
     self.present(vc, animated: true)
 }
like image 151
Parth Adroja Avatar answered Feb 16 '23 23:02

Parth Adroja


You should put the code in which you display the second View Controller in either viewWillAppear() or viewDidAppear().

override func viewDidAppear() {
    super.viewDidAppear()

    var user: String?
    user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String

    if user == "true" {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
        self.show(vc!, sender: vc)
    }

    // Do any additional setup after loading the view, typically from a nib.
}

Reason being that during viewDidLoad() some of the properties of your ViewController has not been defined and it is not ready to present another ViewController.

like image 37
Chan Jing Hong Avatar answered Feb 16 '23 21:02

Chan Jing Hong