Search code examples
iosswiftxcodedowncast

Can't add viewContoller to Tab Bar programmatically in the AppDelegate


I'm trying to add a viewController to the existing Tab Bar programmatically through didFinishLaunchWithOptions, but my code doesn't work, i can't downcast the rootViewController as UITabBarController.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        if let tabBarController = window?.rootViewController as? UITabBarController {
            print("rootVC")
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "NavController")
            vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
            tabBarController.viewControllers?.append(vc)
        }

        return true
    }

Here is my storyboard, i think here is all okay, Tab Bar Contoller is initial view Controller...

Main.storyboard Main.storyboard


Solution

  • In iOS 13+ the window will be nil from didFinishLaunchingWithOptions in the app delegate. Instead move your code to willConnectTo session method in SceneDelegate:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let tabBarController = window?.rootViewController as? UITabBarController {
            print("rootVC")
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "NavController")
            vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
            tabBarController.viewControllers?.append(vc)
        }
        guard let _ = (scene as? UIWindowScene) else { return }
    }