Swift 关闭然后打开导致加载两次

Swift Closing and Then Opening Results in Loading Twice

我在 SO 上查看了几个解决方案,但 none 似乎有效。我有一个问题,当我打开然后关闭一个应用程序时,它连续 "loads" 两次。有没有办法或代码来阻止这种情况发生?该应用程序的配置方式是,当用户关闭然后打开该应用程序时,App Delegate 中的代码将应用程序发送到 "CommandandControlViewController",它决定用户是否已登录,未登录并发送到适当的 ViewController。

func applicationWillEnterForeground(_ application: UIApplication) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let yourVC = mainStoryboard.instantiateViewController(withIdentifier: "CommandAndControlViewController") as! CommandAndControlViewController

    appDelegate.window?.rootViewController = yourVC
    appDelegate.window?.makeKeyAndVisible()
}

可能是 造成的,因为 AppDelegate 有自己的 "window" 属性 而您正在创建另一个 "window" 在 applicationWillEnterForeground 方法中,应用程序将有两个 windows,这可能会导致它加载两次。由于您在 AppDelegate.swift 中,因此无需创建单独的 window 并使用现有的而不编写前两行代码。

我建议在 didFinishLaunchingWithOptions 方法中写下代码的最后 4 行,然后试一试。如下所示:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

      let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
      let yourVC = mainStoryboard.instantiateViewController(withIdentifier: "CommandAndControlViewController") as! CommandAndControlViewController 

       //Below rootViewController is of type UIViewController hence even you don't cast "yourVC" to CommandAndControlViewController it will work

      window?.rootViewController = yourVC
      window?.makeKeyAndVisible()
}