Search code examples
swiftxcodensuserdefaultsappdelegate

Xcode & Swift - unable to instantiate another view controller from AppDelegate


in this app the first time you use it you get 3 welcome pages. After the last one I save a bool to true in UserDefaults in order to skip those welcome pages the next time the user launches the app.

To do that, in AppDelegate.swift I do as following:

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

        if UserDefaultsVault.shared.getDidFinishIntro() == true {

            self.window = UIWindow(frame: UIScreen.main.bounds)
            let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

            let mainVC = storyboard.instantiateViewController(withIdentifier: "mainPage") as UIViewController

            self.window?.rootViewController = mainVC
            self.window?.makeKeyAndVisible()

        } 

        return true
    }

I of course added the storyboard ID to my view controller in the storyboard and I also checked with a breakpoint if the condition is met (and it's true).

Despite this the Main Controller won't instantiate.

I made another app with this code and it's always worked!

Did I mistake something?


Solution

  • For iOS 13+ you need to give the instantiateViewController(withIdentifier:) in SceneDelegate, like this:

    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
    
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            guard let windowScene = scene as? UIWindowScene else { return }
            window = UIWindow(windowScene: windowScene)
            window?.makeKeyAndVisible()
    
            if UserDefaultsVault.shared.getDidFinishIntro() {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                window?.rootViewController = storyboard.instantiateViewController(withIdentifier: "mainPage")
            }
        }
    }
    

    Note: Your code would work for devices using iOS 13 below.