NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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 Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

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

Similar solutions…

Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.