Search code examples
swiftapplication-lifecycle

How to redirect to home screen upon going to background or resuming to the foreground


I just have a quick question regarding app life cycles and programming in Swift. I am trying to return to home screen whenever a user goes to the background. For instance, if a user receives a call or push home button, the app should go back to the main screen it started from instead of where it left off.

func applicationWillEnterForeground(_ application: UIApplication) {
    guard let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(
        withIdentifier: "main") as? MainViewController else { return }
    self.window?.rootViewController?.present(vc, animated: true, completion: nil)
}

Above is the code I have in appDelegate, but somehow it gives an error: Attempt to present ... on ... whose view is not in the window hierarchy!"

Please help me out. Thank you very much!!


Solution

  • Instead of presenting over current rootViewController you need to forget about the last rootViewController. And also it is great to forget about the existing window. Use the code:

    func applicationWillEnterForeground(_ application: UIApplication) {
    
        guard let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(
            withIdentifier: "main") as? UINavigationController else {
                print("NIL VC")
                return
        }
    
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = vc
        self.window?.makeKeyAndVisible()
    }