0

I looked at several solutions on SO but none seem to work. I have a problem where when I open and then close an app, it "loads" twice in a row. Is there a way or code to stop this from happening? The app is configured in such a way that when a user closes and then opens the app, the code in the App Delegate sends the app to a "CommandandControlViewController" which devides whether if a user is Signed In, Not Signed In and sends to the appropriate 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()
}
pacification
  • 5,838
  • 4
  • 29
  • 51
rengineer
  • 349
  • 3
  • 19

1 Answers1

1

This might be causing because AppDelegate has its own "window" property and you are creating another "window" in applicationWillEnterForeground method where app will have two windows, this might be causing it to load twice. Since you are in AppDelegate.swift no need to create separate window and use existing one without writing first two lines of code.

I would suggest to write down last 4 lines of your code in didFinishLaunchingWithOptions method and give it a try. Which will look something like below :

 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()
}
Ganesh Pawar
  • 191
  • 1
  • 12