NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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

Paul Hudson    @twostraws   

Updated for Xcode 12.5

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. For example, this monitors scenePhase and will print out some text into Xcode’s debug console whenever the phase changes:

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:

  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 Emerge

SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.

Set up a demo!

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

Similar solutions…

BUY OUR BOOKS
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!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.