1

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

zeytin
  • 5,545
  • 4
  • 14
  • 38
Khuda
  • 13
  • 2

1 Answers1

1

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 }
}
clawesome
  • 1,223
  • 1
  • 5
  • 10