nastassia
nastassia

Reputation: 897

swift - How to detect from what ViewController application enter background?

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?

Upvotes: 3

Views: 5059

Answers (3)

Parth
Parth

Reputation: 626

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.
}

Upvotes: -2

Gustavo Vollbrecht
Gustavo Vollbrecht

Reputation: 3256

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

Upvotes: 3

Mahak Mittal
Mahak Mittal

Reputation: 131

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)

Upvotes: 1

Related Questions