从后台更新后从视图层次结构中删除以前的视图控制器

Remove previous view controllers from view hierarchy after update from background

我想在从后台更新我的应用程序后从视图层次结构中删除以前的视图控制器。为此,我设置了后台获取完成处理程序。

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)
}

为了重新加载,我从 StoryBoard instantiate ViewController。

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()
}

这种方法可以正确重新加载新的 ViewController。但是,我仍然有以前的视图控制器。下图是我的情况。

关于这个问题有什么想法吗?

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()