Swift Closing and Then Opening Results in Loading Twice

Swift Closing and Then Opening Results in Loading Twice



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




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



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)