iosswiftstoryboardrootviewcontroller

Storyboard's view controller not showing up when programmatically set as root view controller


I am trying to change the rootVC based on some condition on the app launch. All of my VCs are made in the storyboard so I am doing it like this:

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

                    checkPhotoLibraryAccess()

                    return true
                }

func checkPhotoLibraryAccess(){

                    if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.denied ||  PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.notDetermined {
                        showPermissionVC()
                    } else {
                        showContainerVC()
                    }
                }

func showPermissionVC (){

                    let storyboard = UIStoryboard(name: "Main", bundle: nil)

                    let rootVC = storyboard.instantiateViewController(withIdentifier: "askPermissionVC")

                    UIApplication.shared.windows.first?.rootViewController = rootVC

                    self.window?.makeKeyAndVisible()

                }

func showContainerVC (){

                    let storyboard = UIStoryboard(name: "Main", bundle: nil)

                    let rootVC = storyboard.instantiateViewController(withIdentifier: "containerVC")

                    UIApplication.shared.windows.first?.rootViewController = rootVC

                    self.window?.makeKeyAndVisible()

                }

I have removed the arrow showing the initial VC from the storyboard so that it won't have a conflict with the code. However, I got this error and nothing showed up on screen in simulator:

[Application] Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?

I have now removed the "Main storyboard file base name" property from info.plist. This time the error is gone but still nothing is showing up. What am I doing wrong?


Solution

  • You need to initialize the window programmatically.

    Try adding the following to the beginning of your didFinishLaunchingWithOptions method in Appdelegate

    self.window = UIWindow()
    

    Also in your showPermissionVC and showContainerVC methods, replace this line:

    UIApplication.shared.windows.first?.rootViewController = rootVC
    

    with:

    window?.rootViewController = rootVC