3

In my swift app I need to know from what screen my application entered background. Im trying to use NotificationCenter this way:

class MainViewController: UIViewController{
   override func viewDidLoad() {
        super.viewDidLoad()
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(appMovedToBackgroundMain), name: UIApplication.didEnterBackgroundNotification, object: nil)
    }

    @objc func appMovedToBackgroundMain() {
        print("main - App moved to Background!")
    }
}

class InitViewController: UIViewController{
       override func viewDidLoad() {
            super.viewDidLoad()
            let notificationCenter = NotificationCenter.default
            notificationCenter.addObserver(self, selector: #selector(appMovedToBackgroundInit), name: UIApplication.didEnterBackgroundNotification, object: nil)
        }

        @objc func appMovedToBackgroundInit() {
            print("init - App moved to Background!")
        }
    }

and when I'm press Home button at the MainViewController I got in Xcode's console these lines:

init - App moved to Background!
main - App moved to Background!

and I expected only one line there - main - App moved to Background!. How can I reach this?

nastassia
  • 807
  • 1
  • 12
  • 31
  • Just remove the observer that is not in use. After the Init View is done it should remove the observer. You'll end up with only Main view added as an observer. Voila! – Haroun Hajem Mar 22 '22 at 21:43

3 Answers3

3

On AppDelegate Methods: applicationDidEnterBackground or applicationWillEnterForeground, you can get the top most UIViewController. It is well explained on this question: Get top most UIViewController

Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37
1

You can use following function:

 func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

Here you can check which controller is on the top in your navigation controller's controller.

print(self.navigationController.topViewController)
Mahak Mittal
  • 121
  • 1
  • 10
-2

When application enter in background state below method will call.

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
Parth
  • 634
  • 8
  • 15
  • function `applicationWillEnterForeground ` belongs to UIApplicationDelegate and it is not accessible from ViewController – gondo May 27 '20 at 08:05