1

Upon first downloading my app, I want to push a different view controller (such as a tutorial view controller), then after opened again, I want to push my normal view controller upon launching. In swift, the way I push a view controller is the following:

func application(_ application: UIApplication, 
didFinishLaunchingWithOptions launchOptions: 
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.main.bounds)
    window!.rootViewController = ViewController()
    window!.makeKeyAndVisible()

    return true
}

So intuitively, maybe something like this:

func application(_ application: UIApplication, 
didFinishLaunchingWithOptions launchOptions: 
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.main.bounds)

    if firstRun == true {
        window!.rootViewController = LaunchViewController()
        window!.makeKeyAndVisible()
    } else {
        window!.rootViewController = ViewController()
        window!.makeKeyAndVisible()
    }

    return true
}

1 Answers1

2

You can try to save that state in UserDefaults

if !UserDefaults.standard.bool(forKey: "LaunchedBefore") {
    window!.rootViewController = LaunchViewController()
    UserDefaults.standard.set(true, forKey: "LaunchedBefore")
} else {
    window!.rootViewController = ViewController()

}
window!.makeKeyAndVisible()
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Great! So apparently SO will only let me accept an answer after 15 minutes, haha. So I'll use this time to double check if I understand your code. So you create some boolean var, which is referenced by a key ("LaunchedBefore"), then after pushing the LaunchVC the first time, you change it's value to true, thus at the next launch, VC is pushed. –  Feb 27 '19 at 16:00
  • Also keep in mind default value of bool keys that doesn't exists in `UserDefaults` is `false` – Shehata Gamal Feb 27 '19 at 16:02
  • Right, I see. Thank you! –  Feb 27 '19 at 16:08