How to detect when your app moves to the background or foreground with scenePhase
About 2 min
How to detect when your app moves to the background or foreground with scenePhase 관련
SwiftUI by Example
Back to Home
How to detect when your app moves to the background or foreground with scenePhase | SwiftUI by Example
How to detect when your app moves to the background or foreground with scenePhase
Updated for Xcode 15
SwiftUI provides a scenePhase
environment key that is automatically updated as your app moves between the foreground, background, and inactive states. You can watch for these in your App
struct itself, or in any SwiftUI view.
First, add a property to track the key:
@Environment(\.scenePhase) var scenePhase
And now either add any logic you want to your body, or use onChange()
to observe changes directly.
As an example, we could write a view that monitors scenePhase
and prints out some text into Xcode's debug console whenever the phase changes:
struct ContentView: View {
@Environment(\.scenePhase) var scenePhase
var body: some View {
Text("Example Text")
.onChange(of: scenePhase) { newPhase in
if newPhase == .inactive {
print("Inactive")
} else if newPhase == .active {
print("Active")
} else if newPhase == .background {
print("Background")
}
}
}
}
As you can see, there are three states:
- The Active state is used when your app is in the foreground and interactive for the user, meaning that they are using it right now.
- The Background state is used when your app isn't currently visible, so you should cut back the amount of work you do.
- The Inactive state is used when your app is visible, but not directly interactive to the user. For example, if you enter multi-tasking mode while running the app – you can see your app's window alongside others, but you're not directly using it.
Similar solutions…
How to provide visual structure using foreground styles | SwiftUI by Example
How to provide visual structure using foreground styles
How to customize the background color of navigation bars, tab bars, and toolbars | SwiftUI by Example
How to customize the background color of navigation bars, tab bars, and toolbars
How to change the background color of List, TextEditor, and more | SwiftUI by Example
How to change the background color of List, TextEditor, and more
How to set the background color of list rows using listRowBackground() | SwiftUI by Example
How to set the background color of list rows using listRowBackground()
How to run code when your app launches | SwiftUI by Example
How to run code when your app launches