Perform Segue in ViewDidLoad [duplicate]

好久不见. 提交于 2019-12-19 05:24:14

问题


I`m trying to perform a segue if its the first time the app is loading. I can see my print message in the debugger, but the Perform Segue is not working. I don't get any errors. Can somebody please tell me whats wrong?

import UIKit
import LocalAuthentication
let isFirstLaunch = UserDefaults.isFirstLaunch()
extension UserDefaults {
    // check for is first launch - only true on first invocation after app install, false on all further invocations
    // Note: Store this value in AppDelegate if you have multiple places where you are checking for this flag
    static func isFirstLaunch() -> Bool {
        let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag"
        let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag)
        if (isFirstLaunch) {

            UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag)
            UserDefaults.standard.synchronize()
        }
        return isFirstLaunch
    }
}

class loginVC: UIViewController {





    override func viewDidLoad() {

        super.viewDidLoad()

        if  isFirstLaunch == false {
          performSegue(withIdentifier: "setPassword", sender: self)
            print("testFalse") }
            else {
            performSegue(withIdentifier: "setPassword", sender: self)
            print("testTrue")}


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




    }

回答1:


You can't use performSegue() from within viewDidLoad(). Move it to viewDidAppear().

At viewDidLoad() time, the current view isn't even attached to the window yet, so it's not possible to segue yet.




回答2:


I think you can also put your segue into a Dispatch.main.async

    DispatchQueue.main.async {
        if  isFirstLaunch == false {
            performSegue(withIdentifier: "setPassword", sender: self)
            print("testFalse") 
        } else {
            performSegue(withIdentifier: "setPassword", sender: self)
            print("testTrue")
        }
    }



回答3:


You can also use a different approach - change the main window's rootViewController to the view controller of your choice depending on isFirstLaunchboolean

UIApplication.shared.keyWindow?.rootViewController = setPasswordViewController



来源:https://stackoverflow.com/questions/45653825/perform-segue-in-viewdidload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!