My ViewDidLoad method on a ViewController is called twice, but only in a particular scenario. There are two view controllers which I need to present, one if user isn't logged in and the second if the user is logged in. I am using storyboard and have set a navigation controller as initial view controller in it.
In my AppDelegate didFinishLaunchingWithOptions method I have populated ViewControllers array with the desired controller as below
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navigationController = storyboard.instantiateViewController(withIdentifier: "navController") as! UINavigationController
if UserDefaults.standard.object(forKey: USERID) != nil {
viewController = storyboard.instantiateViewController(withIdentifier: "HomeVC_ID") as! HomeVC
}
else {
viewController = storyboard.instantiateViewController(withIdentifier: "LoginVC_ID") as! LoginVC
}
navigationController.viewControllers = [viewController] as! [UIViewController]
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
ViewDidLoad method in HomeVC is called twice, whereas it's called just once for LoginVC.
I already tried searching through articles viewDidLoad is called twice and viewDidLoad getting called twice on rootViewController at launch but couldn't corner the issue.
When you create your navigation view controller from the storyboard, this already contains it's
rootViewController(which must not to be confused with therootViewControllerof theUIWindow). I guess this is yourHomeVC(in the storyboard). So, the storyboard magic already createsHomeVC, and you do not have to create it manually indidFinishLaunchingWithOptions.If you have specify the storyboard as your main interface in the project's/target's properties, you do not need any creational code in
didFinishLaunchingWithOptionsand just let the framework perform the magic.If you want to do this programatically, then - in the storyboard - you should remove the navigation controller, and create it manually (not via
instantiateViewController) indidFinishLaunchingWithOptions. You would also add the appropriate root view controller here (instantiated from the storyboard), maybe like this: