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

时间:2018-03-13 12:10:56

标签: ios swift background-process

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

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。但是,我仍然有以前的视图控制器。下图显示了我的情况。

enter image description here

关于这个问题的任何想法?

1 个答案:

答案 0 :(得分:4)

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