Search code examples
iosswiftswift5appdelegateuserdefaults

User Defaults Won't Instantiate View Controller


When a user logs into my app, a Swift UserDefault is saved for the key "isLogged" and set to the true. My goal is to have the app delegate show a different view controller if the value of this UserDefault is true.

I've been struggling for weeks to get this running and thus wanted to see if anyone knew any issues. I'm calling a function in my AppDelegate.swift to instantiate the view controller, but for some reason the view controller is never shown. The print statement is executed, so I know the value is being set, but why is the view controller not being shown?

func application(_ application: UIApplication,
               didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

  checkDefault()

  return true
}

func checkDefault() {
   if (UserDefaults.standard.bool(forKey: "isLogged") == true) {
     print("LoggedIn is true")
     let vc = UIStoryboard(name: "Main", bundle:  
     Bundle.main).instantiateViewController(withIdentifier: 
     "parent_vc") as! ParentHomeViewController

     let navVC = UINavigationController(rootViewController: vc)
     let share = UIApplication.shared.delegate as? AppDelegate
     share?.window?.rootViewController = navVC
     share?.window?.makeKeyAndVisible()
 }
}

Thank you!


Solution

  • You should call your checkDefault() in SceneDelegate.swift .

    to be exact you have to call the func in,

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
    

    For further reading and understanding, you can use this https://medium.com/@kalyan.parise/understanding-scene-delegate-app-delegate-7503d48c5445 for reference.