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
switch
newScenePhase {
case .active:
//open QR Scanner when app is resumed
self.QRScannerisPresented = true
return
case
.background:
//app moves to backgound
return
case
.inactive:
return
@unknown
default:
return
}
}

And voilà !

🇨🇭Cybersecurity student. DJ & Musician. Interested about too much things. Improving every minute.