Ios 快速关闭然后打开导致两次加载

Ios 快速关闭然后打开导致两次加载,ios,swift,viewcontroller,Ios,Swift,Viewcontroller,我研究了几个解决方案,但似乎都不起作用。我有一个问题,当我打开然后关闭一个应用程序时,它会连续加载两次。有没有办法或代码阻止这种情况发生?应用程序的配置方式是,当用户关闭然后打开应用程序时,应用程序委托中的代码会将应用程序发送到CommandControlViewController,该命令会确定用户是否已登录,是否未登录,并发送到相应的ViewController func applicationWillEnterForeground(_ application: UIApplication)

我研究了几个解决方案,但似乎都不起作用。我有一个问题,当我打开然后关闭一个应用程序时,它会连续加载两次。有没有办法或代码阻止这种情况发生?应用程序的配置方式是,当用户关闭然后打开应用程序时,应用程序委托中的代码会将应用程序发送到CommandControlViewController,该命令会确定用户是否已登录,是否未登录,并发送到相应的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有自己的窗口属性,而您正在applicationWillEnterForeground方法中创建另一个窗口,其中应用将有两个窗口,这可能会导致它加载两次。由于您在AppDelegate.swift中,因此无需创建单独的窗口并使用现有窗口,无需编写前两行代码

我建议用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()
}