Detect when your app is sent to the background in UIKit


Greetings, traveler!

Sometimes, we must change an application’s behavior based on its current state. Let’s examine how to do this in UIKit.

Note

By the way, if you want to learn how to do it in SwiftUI, you can check out this article.

The AppDelegate.swift file contains a suitable method called applicationWillResignActive(). We can use NotificationCenter to subscribe to this event.

NotificationCenter.default.addObserver(
    self,
    selector: #selector(action),
    name: UIApplication.willResignActiveNotification,
    object: nil
)

@objc
func action() {
    // do something...
}

Conclusion

And that’s it! We will now receive a notification that will help us update our module’s state.