FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to detect when your app moves to the background or foreground with scenePhase

Paul Hudson    @twostraws   

Updated for Xcode 13.0

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 {
                } else if newPhase == .active {
                } else if newPhase == .background {

Download this as an Xcode project

As you can see, there are three states:

  1. 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.
  2. The Background state is used when your app isn’t currently visible, so you should cut back the amount of work you do.
  3. 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.
Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.