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?
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)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With