Search code examples
iosswiftxcodeautolayoutstoryboard

How to set the Initial viewController in AppDelegate Programatically?


I know that this question was asked a couple of times but I tried all the solutions and nothing really worked for me.

I am currently working on an iOS Project and encountered a problem.

I am building an App which needs some personal information at the first launch. Therefore I use a NavigationController which I set to be the Initial View Controller in Storyboard.

Now I would like to check in my AppDelegate whether the User already entered the Personal Data. In this case I created a User Defaults KV Pair called "onboarding" of type Bool

If the Value is true, I would like to change the Initial View Controller to the main TabBarController, the rest of the App uses.

I hope this image can illustrate what I meant above: enter image description here

I hope you can think of a way to solve this problem.

Thanks a lot for your help in advance. Have a great day!


Solution

  • 1) Open your AppDelegate.swift and add property

    var window: UIWindow?
    

    2) In

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
    

    a) initialize this window:

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

    b) set UIViewController you needed to window's rootViewController property:

    window?.rootViewController = myViewController
    

    c) make this window key and visible:

    window?.makeKeyAndVisible()
    

    That is all. And don't forget to remove your storyboard from target settings: Remove storyboard from target

    Hope its help.