简体   繁体   中英

Is there a way to navigate to another page while on func viewDidLoad() using Swift?

Upon opening my app, I want to be able to check if the UserDefaults.standard has a value on two different variables. If these variables are blank, the rest of the class will continue, but if these two variables have values, I want to navigate to another page. Is it possible to do this through viewDidLoad()? I was thinking of using viewDidLoad() because I had wanted the page change to happen before the user ends up viewing this.

This is what I have so far

    override func viewDidLoad() {
        super.viewDidLoad()

        let preferences = UserDefaults.standard

        if preferences.string(forKey: "useremail") != "" || preferences.string(forKey: "usernumber") != "" {
            transitionToMain()
        }
    }
    func transitionToMain() {

        let mainPage =
        storyboard?.instantiateViewController(withIdentifier: Constants.Storyboard.mainPage) as? MainPage

        view.window?.rootViewController = mainPage
        view.window?.makeKeyAndVisible()
    }

However, when I have tried running this, the page remains the same and does not change. The code I have for transitionToMain is what I have upon clicking buttons, and it works in those cases, but it does not for this. Is there a better way to go about this? What could be improved on so that this can properly work?

Thank you very much in advance.

if you want to call this in the viewDidLoad function then you must use the window reference from appDelgate since windows is nil because is not added to a window yet,

func transitionToMain() {

    let mainPage =
    storyboard?.instantiateViewController(withIdentifier: Constants.Storyboard.mainPage) as? MainPage
    let appDelgate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = mainPage
    appDelegate.window?.makeKeyAndVisible()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM