How to update the value of a state variable when app lifecycle changes in SwiftUI ?

I created a QR Code Scanner app in Swift to scan QR codes and check them against a custom backend. The app is quite simple : it has a two view. The QR Scanner is a UIKit view wrapped in a UIViewController component and presented as a sheet that can be opened/closed from the main view.

At some point, I faced the following issue and struggled to find simple answer : I wanted to be able to open the sheet with the embed scanner each time the app is opened/resumed from background. The state of the sheet is controlled by a state variable in the ContentView. Thanks to SwiftUI, it turns out the answer is very easy :

1. We need to inject the presentationMode environment variable in our ContentView :

@Environment(\.presentationMode) private var presentationMode

2. We can then use the onChange hook and write a simple switch statement that will return the current state of our application. This enables us to set the state of our variable when the application is moved from background to foreground.

.onChange(of: scenePhase) { newScenePhase in
newScenePhase {
case .active:
//open QR Scanner when app is resumed
self.QRScannerisPresented = true
//app moves to backgound

And voilà !

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store