SwiftUI - Lifecycle Methods

When it comes to app development, the application lifecycle is crucial. There are lifecycle methods for dealing with these lifecycle events. Using these lifecycle methods, we can perform specific tasks whenever the application's state changes. For example, when the app goes to the background, when it is terminated, or when it becomes active.

In an iOS project, these lifecycle methods are defined in the AppDelegate file. However, when we create a new Xcode project with SwiftUI chosen as the interface, we only get a struct annotated with the @main keyword (indicating that it is the app's starting point) and a ContentView file, but the AppDelegate file is missing. So how do we handle the lifecycle events in SwiftUI?

Throughout this blog, you will learn the SwiftUI equivalents of the AppDelegate lifecycle methods and also how they are defined in a SwiftUI Project.

Lifecycle methods

Initial configuration for any application, like initializing an analytics service such as Firebase or setting up Sentry, is done in the application delegate's didFinishLaunchingWithOptions method. It is the first method that is called when the app becomes active. In SwiftUI this can be achieved by creating an initializer for the main App struct.

Generally, applicationDidBecomeActive, applicationWillResignActive, and applicationDidEnterBackground  methods of the AppDelegate are used to track the state of the application. In SwiftUI, the scene's state is tracked using environment values, which can be accessed using the @Environment property wrapper. We can listen to the changes using the onChange method which provides the state of the current scene. The possible values for the phase variable are background, active, and inactive. The closure provided to the onChange method is called with the updated phase value whenever the state changes.

For views, we can use the onAppear and onDisappear methods which function similar to the viewDidAppear and viewDidDisappear  methods.

How to use AppDelegate with SwiftUI?

Some lifecycle methods are still not supported in SwiftUI. For example, the didReceiveRemoteNotification method. So, for such methods, SwiftUI has provided a way to use the old AppDelegate using the @UIApplicationDelegateAdaptor property.

In the above example, SwiftUI takes care of initializing the AppDelegate class and calling the delegate methods.

This way any of the AppDelegate methods can be used in SwiftUI.

For more information regarding lifecycle methods in SwiftUI, you can refer to this page.

Dhruv Tailor

Dhruv Tailor

Software Engineer developing mobile apps at PLG Works
Surat, Gujarat