Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What UIViewController method is called when opening app from background?

Is there any conventient way of determining if a view is being loaded from the app being in background mode?

In 3.X I would rely on viewDidLoad to do some initalization etc., this however is not the case for 4.X, as you cannot rely for the viewDidLoad method to be called.

I would like to avoid putting in extra flags to detect this in the appdelegate, I would rather use a reliable way of doing this in the UIViewController, but cannot seem to find anything in the lifecycle of a UIViewController that could help me out here.

Any ideas? How do you handle such situations?

like image 828
Kaspa Avatar asked Sep 04 '10 18:09

Kaspa


2 Answers

Swift 5

Subscribe to Notification


       NotificationCenter.default.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

        @objc func appMovedToForeground() {
            //Your code here
        }

Remove Notification


    override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)

            NotificationCenter.default.removeObserver(self)
    } 

like image 52
lukas Avatar answered Sep 28 '22 13:09

lukas


UIViewController's lifecycle has no methods that will be called when moving an app from background to foreground.

When you want this event to trigger some specific block of code you need to add an observer for notification named Notification.Name.UIApplicationWillEnterForeground. An example of this would be:

NotificationCenter.default.addObserver(self, selector: #selector(appMovedToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)

@objc func appMovedToForeground() {
    //Your code here
}

Keep in mind that you will need to remove the observer to prevent it from triggering throughout the application.

like image 40
Dominik Babić Avatar answered Sep 28 '22 13:09

Dominik Babić