< How to let the user select multiple dates | How to respond to view lifecycle events: onAppear() and onDisappear() > |
Updated for Xcode 14.0 beta 1
New in iOS 14
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")
}
}
}
}
Download this as an Xcode project
As you can see, there are three states:
SPONSORED In-app subscriptions are a pain. The code can be hard to write, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.