Search code examples
swiftviewviewcontrollerlaunch

show the second ViewController when app launch the second time


so when i launch my app the first time there is a welcome ViewController. How can i set a function, that shows the second ViewController when the user launches the app the second time.


Solution

  • Add a Boolean in the user default in your application to check whether the application is launch first time or not. Based on this Boolean value load another ViewController in your app delegate class.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
         let isFirst = UserDefaults.standard.bool(forKey: “isLaunched”) // edited this after rmaddy's comment 
         var viewControllerWithIdentifier = "SecondViewController"
         if !isFirst {
            UserDefaults.standard.set(true, forKey: “isLaunched”)
            viewControllerWithIdentifier = "FirstViewController"
         }
         let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
         let initialViewController : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier(viewControllerWithIdentifier) as UIViewController
         self.window = UIWindow(frame: UIScreen.main.bounds)
         self.window?.rootViewController = initialViewController
         self.window?.makeKeyAndVisible()
         return true
    }