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.




    }
Dennis Vennink
  • 1,083
  • 1
  • 7
  • 23
Paal Aune
  • 353
  • 5
  • 10

2 Answers2

43

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.

Smartcat
  • 2,834
  • 1
  • 13
  • 25
  • Thank you Smartcat. Moved the code to ViewDidAppear() and it works fine now! – Paal Aune Aug 12 '17 at 19:59
  • Is it okay to call it from viewWillAppear do you know? It's testing okay for me but I'm worried about outlier cases or low-performance devices... – paul_f Jun 24 '19 at 21:22
  • 1
    @paul_f I've successfully done so in some of my production code, but others have had trouble. See this [SO](https://stackoverflow.com/a/37493606/8441876) for example. Maybe it depends on if there's a transition animation to be used? If you spot something definitive from Apple, please post here. – Smartcat Jun 25 '19 at 17:52
  • @Smartcat you literally saved me a headache. Worst part is that I was really close, but I was approaching the problem in the wrong way. I was trying to run `performSegue` inside `viewWillAppear`. Just moving it to `viewDidAppear` fixed everything. – Mihail Minkov Oct 17 '19 at 14:54
1

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

cohen72
  • 2,830
  • 29
  • 44