Skip to content
DeveloperMemos

How to Use scenePhase in SwiftUI

SwiftUI, scenePhase1 min read

With the release of iOS 14, SwiftUI introduced a new property wrapper called @SceneStorage, which allows you to save and restore the state of a view across multiple launches of an app. However, this feature only works if the scene is not destroyed by the system when the app is not in the foreground. This is where scenePhase comes in. In this article, we will explore how to use scenePhase in SwiftUI.

What is scenePhase?

scenePhase is a new property in the Scene struct that represents the current phase of a scene's life cycle. A scene is an instance of a view hierarchy that represents a single user interface in an app. A scene can be in one of four different phases:

  • inactive: The scene is not visible to the user, but it is still in memory.
  • active: The scene is visible to the user and is receiving events.
  • background: The scene is still in memory, but it is not visible to the user.
  • terminated: The scene has been removed from memory.

By using scenePhase, you can respond to changes in the scene's life cycle and perform appropriate actions. For example, you might want to save the state of a view when the scene moves from the active to the inactive phase, and restore it when the scene becomes active again.

Using scenePhase in SwiftUI

To use scenePhase in SwiftUI, you need to add it to the Scene struct in your app's App file. Here's an example:

1@main
2struct MyAwesomeApp: App {
3 @Environment(\.scenePhase) private var scenePhase
4
5 var body: some Scene {
6 WindowGroup {
7 ContentView()
8 }
9 .onChange(of: scenePhase) { phase in
10 switch phase {
11 case .active:
12 // Do something when the scene becomes active
13 case .inactive:
14 // Do something when the scene becomes inactive
15 case .background:
16 // Do something when the scene moves to the background
17 case .terminated:
18 // Do something when the scene is terminated
19 @unknown default:
20 // Do something when a new phase is introduced in future iOS versions
21 }
22 }
23 }
24}

In this example, we are using the @Environment property wrapper to inject the scenePhase property into our app. We then use the onChange modifier to respond to changes in the scene's phase.

Inside the closure passed to onChange, we use a switch statement to handle each of the possible phases. In each case, you can perform appropriate actions based on the current phase of the scene.

Conclusion

Using scenePhase in SwiftUI allows you to respond to changes in the life cycle of a scene and perform appropriate actions. By using this property, you can save and restore the state of a view across multiple launches of an app. This is a powerful tool that can help you create more robust and user-friendly apps.