How to listen to changes in Phases in a SwiftUI app

Oscar de la Hera Gomez
Two flowers that represent SwiftUI and XCode side by side with the text "SwiftUI Scene Phases" beneath it.

Use an onChange modifier that listens to a "scenePhase" environment variable to listen for when the app becomes active, inactive or goes to the background.

The following tutorial has been made available through the tutorials/phases/101 branch on our Open Source Swift Starter Project.

A screenshot of XCode showing the code found below. On the bottom you can see how the app logged the three events: active, inactive and background.

The code below demonstrates how to listen for scene phase changes such as when a SwiftUI app becomes active, inactive or goes into the background.

Please note that although the code has been applied to a WindowGroup, it can also be applied to a View.

Looking to learn more about things you can do with Swift, SwiftUI or XCode ?

Search our blog to find educational content on learning how to use Swift, SwiftUI or XCode.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details