How to listen to changes in Phases in a SwiftUI app

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.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 10/18/2024 at 13:52
Last Updated on 10/20/2024 at 10:35
<p>Two flowers that represent SwiftUI and XCode side by side with the text "SwiftUI Scene Phases" beneath it.</p>

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.

SubscribeDownload Open Source Project

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

View Repository
<p>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.</p>

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.

Search our Blog

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe