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

3.6k views Asked by At

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.
}
4

There are 4 answers

0
Parth Adroja On BEST ANSWER

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)
 }
0
miOS On

Instead of writing logic in viewDidLoad, write it before presenting the current viewcontroller

e.g. If you want to check it on app launch, check if the user is logged-in in didFinishLaunching method and set the rootViewController accordingly.

If want to present it from some other viewController, first check the user login status and present the viewcontroller accordingly instead of check in viewDidLoad.

Also you can present the viewcontroller by performing operation after some delay.

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
        // present view contoller
    }
0
Chan Jing Hong On

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.

0
Hamish On

You need to make it Async, there is no need for any delay, just like this:

 override func viewDidLoad() {
    super.viewDidLoad()

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

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

}