Kaspa
Kaspa

Reputation: 2209

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?

Upvotes: 11

Views: 10928

Answers (4)

grabz
grabz

Reputation: 87

Combine approach should be:

private var cancellables: Set<AnyCancellable> = []

NotificationCenter.default
            .publisher(for: UIApplication.willEnterForegroundNotification, object: nil)
            .sink { [weak self] _ in
                print("app just returned to the foreground")
            }
            .store(in: &cancellables)

Upvotes: 1

lukas
lukas

Reputation: 214

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

Upvotes: 9

Dominik Babić
Dominik Babić

Reputation: 71

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.

Upvotes: 3

Henrik P. Hessel
Henrik P. Hessel

Reputation: 36647

- (void)viewWillAppear:(BOOL)animated

but not

- (void)viewDidLoad

The Application Delegate Method

- (void)applicationWillEnterForeground:(UIApplication *)applicationUIApplicationDelegate

will be called after the the application entered the foreground though you can add an observer for the UIApplicationWillEnterForegroundNotification in any of your views.

Upvotes: -7

Related Questions