1

I need to return to my rootViewController when the app move from background to foreground. So in applicationWillEnterForeground I have written this code:

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let mainController = storyboard.instantiateViewController(withIdentifier: "MqttLoginController")
        window?.rootViewController = mainController

But I don't understand why in my rootViewController is called firstly viewDidAppear, then viewDidLoad and finally viewDidAppear again. Why is this happening?

UPDATE: For clarification, I haven't written that I don't use navigation controller in the initial screens of the app, and I need to come back to my initialViewController. So it's not really the rootViewController of all screens.

Silvia
  • 21
  • 2

2 Answers2

1

The ViewController is already present as the root. Hence, when your app comes to foreground it fires viewDidAppear then you are creating a new instance of ViewController, this fires the viewDidLoad and when it appears viewDidAppear once again.

Frankenstein
  • 15,732
  • 4
  • 22
  • 47
  • I thought so, but if I debug it firstly appear the last screen before the app moved to background (no viewDidAppear of my initialViewController). Then goes my code in applicationWillEnterForeground, then viewDidAppear, viewDidLoad, viewDidAppear of the initialViewController. – Silvia May 21 '20 at 07:56
0

Instead of creating a new instance try to use this code

 if let root =  window?.rootViewController {
        root.navigationController?.popToRootViewController(animated: true)
     }
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
  • I've updated my question, unfortunately the desired screen I want to come back to is not the rootViewController of all views, but it's the initialViewController. – Silvia May 21 '20 at 07:58