Reputation: 323
I'm trying to change root ViewController of my app programmatically. Once user registers I want different root ViewController. This is my code
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "tabBarVC")
UIApplication.shared.keyWindow?.rootViewController = vc
UIApplication.shared.keyWindow?.makeKeyAndVisible()
self.present(vc, animated: true, completion: nil)
After vc
is presented I kill the app, and when I run it again the root ViewControler is the same. What am I doing wrong? I also tried the same code in AppDelegate, but no success.
Upvotes: 1
Views: 5671
Reputation: 100503
Set this in appDelegate's didFinishLaunchingWithOptions
method according to current app settings , also you should use window
not keyWindow
if(userExists)
{
let vc = storyboard.instantiateViewController(withIdentifier: "tabBarVC")
UIApplication.shared.window.first?.rootViewController = vc
}
else
{
let vc = storyboard.instantiateViewController(withIdentifier: "loginVC")
UIApplication.shared.window.first?.rootViewController = vc
}
Don't use present as this will automatically change the root
Also another way to access windows (used when AppDelegate has a value)
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeController = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
appDelegate?.window?.rootViewController = homeController
Upvotes: 1