Hooking into App’s Lifecycle  within UIViewController

Hooking into App’s Lifecycle  within UIViewController

Requirement

I’m building an application in which I would like to play an animation when the (root) view controller comes into the foreground and pause it when it (app) goes to the background.

The Platform

iOS exposes the Application Delegate that provides callback methods to hook into in response to the application’s foreground/background transition. This is great if all you want to do is write application-wide logic. In this article, I discuss how I handled a view controller specific logic in response to the application’s lifecycle events.

Approach

Luckily for me, the platform sends notifications in response to a change in app’s lifecycle events as highlighted in the documentation:

  • didBecomeActiveNotification: Posted when the app becomes active.
  • didEnterBackgroundNotification: Posted when the app enters the background.
  • willEnterForegroundNotification: Posted when the app is entering the foreground.
  • willResignActiveNotification: Posted when the app is no longer active.
  • willTerminateNotification: Posted when the app is about to terminate.

A typical usage registers the containing view controller as an observer to the desired notification perhaps in the init method. The registration also takes an objc method to callback when the notification is received.

NotificationCenter.default.addObserver(self, selector: #selector(onAppDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)

Your callback method in the view controller will have such a signature:

@objc func onAppDidEnterBackground() {
   // some awesome logic
}

Conclusion

This works for me since the view controller is the root controller. For modally presented view controllers, I can, and probably would, use the view* lifecycle callbacks to achieve the same e.g. viewWillDisappear().