如何在Appdelegate中关闭ViewController?

时间:2018-07-11 09:42:42

标签: ios swift viewcontroller appdelegate

我为这样的暂停视图创建launchScreen。

func applicationWillResignActive(_ application: UIApplication) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let launchScreen = storyboard.instantiateViewController(withIdentifier: "launchScreen")
        launchScreen.restorationIdentifier = "launchScreen"

        var rootViewController = UIApplication.shared.keyWindow?.rootViewController
        while let presentController = rootViewController?.presentedViewController {
            rootViewController = presentController
        }
        rootViewController?.present(launchScreen, animated: false, completion: nil)
    }

func applicationDidEnterBackground(_ application: UIApplication) {

            guard let passcodeManageView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "passcodeManageView") as? PasscodeManageViewController else { return }
            passcodeManageView.state = State.loginMode
            passcodeManageView.modalPresentationStyle = .overFullScreen

            var rootViewController = UIApplication.shared.keyWindow?.rootViewController
            while let presentController = rootViewController?.presentedViewController {
                rootViewController = presentController
            }
            rootViewController?.present(passcodeManageView, animated: false, completion: nil)

    }

但是,如何在applicationDidEnterBackground(:_)中关闭launchScreen?

我如何找到特定的视图控制器并将其关闭?

1 个答案:

答案 0 :(得分:3)

根据Apple document for applicationDidEnterBackground(_:)`

  

使用此方法释放共享资源,使计时器无效,并存储足够的应用程序状态信息,以防您的应用程序在以后终止时恢复到当前状态。 您还应该禁用对应用程序用户界面的更新,并避免使用某些类型的共享系统资源(例如用户的联系人数据库)。还必须避免在后台使用OpenGL ES。

应用进入后台后,您不应该关闭启动屏幕。但是,如果您仍然想实现它,请使用window?.rootViewController?退出,因为此时window?.rootViewController?是启动屏幕

func applicationDidEnterBackground(_ application: UIApplication) {
  if (window?.rootViewController?.isKind(of: YOUR_LAUNCH_SCREEN_CLASS.self))! {
    window?.rootViewController?.dismiss(animated: true, completion: nil)
  }
}