Search code examples
iosswiftbackground-process

Remove previous view controllers from view hierarchy after update from background


I want to remove previous view controllers from view hierarchy after update my app from background. To achieve this, I set background fetch completion handler.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  
  UIApplication.shared.setMinimumBackgroundFetchInterval(1200)
  return true
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // reload occur
        reloadApp()
        completionHandler(.newData)
}

For reloading, I instantiate ViewController from StoryBoard.

func reloadApp() {

   // previous ViewController Stack has not been removed.

   let rootStoryBoard = UIStoryboard(name: "Main", bundle: nil)
   let rootVC = rootStoryBoard.instantiateViewController(withIdentifier: "MainTabBarController")
    rootVC.view.layoutIfNeeded()
    UIApplication.shared.keyWindow?.rootViewController = rootVC
    UIApplication.shared.keyWindow?.makeKeyAndVisible()
}

This approach reloads new ViewController correctly. But, I still have previous view controllers. Below image shows my situation.

enter image description here

Any ideas about this problem?


Solution

  • if let therootController = UIApplication.shared.keyWindow?.rootViewController {
        // If rootViewcontroller is navigationController then pop to root if any controllers has been pushed, dismiss if any controllers has been presented.
    }
    UIApplication.shared.keyWindow?.rootViewController = nil
    let rootStoryBoard = UIStoryboard(name: "Main", bundle: nil)
    let rootVC = rootStoryBoard.instantiateViewController(withIdentifier: "MainTabBarController")
    rootVC.view.layoutIfNeeded()
    UIApplication.shared.keyWindow?.rootViewController = rootVC
    UIApplication.shared.keyWindow?.makeKeyAndVisible()