Hooking into App’s Lifecycle within UIViewController

Software Engineer
Search for a command to run...

Software Engineer
No comments yet. Be the first to comment.
Introduction Last week, the Swift for Android working group announced that Swift now supports Android. This is an exciting milestone for developers who want to leverage Swift's powerful features in Android development. To help developers explore this...

In my previous article, I introduced the Swift Android Gradle Plugin that simplifies integrating Swift code into Android projects. To demonstrate the plugin in action, I built a sample Android app that generates fractal images using Swift and renders...

Taking Flight with Android XR: Building a Jetliner Demo I spent the last few days exploring Android XR, Google's latest platform for extended reality applications. After working through the documentation and experimenting with the SDK, I built a demo...

This article shows you how to eliminate the rebuild-test cycle when working with Android preferences. Pref Editor lets you modify values instantly.

The Iterator design pattern is a well-known and often-used pattern. It allows us to access elements in a collection without the need to know about the underlying storage details. We get this functionality from an object known as an iterator of the co...

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.
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.
Luckily for me, the platform sends notifications in response to a change in app’s lifecycle events as highlighted in the documentation:
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
}
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().