This question already has an answer here:
- Perform Segue on ViewDidLoad 12 answers
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.
}
I think you can also put your segue into a
Dispatch.main.async
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.
You can also use a different approach - change the main window's
rootViewController
to the view controller of your choice depending onisFirstLaunch
booleanUIApplication.shared.keyWindow?.rootViewController = setPasswordViewController