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.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

CardView in IOS (Swift & SwiftUI)

How performance monitoring is done right for iOS App

Overlapping Core Haptic Events

SwiftUI in Production

SwiftUI Tutorial – How to create Spinners in Xcode 12 Part 2

Check if a Swift Array Is Empty: Best Practice Revisited

The way of demonstration the UIKit-written UI by using SwiftUI wrapper

x

Custom Drop Down Text Field in SWIFTUI

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
Valentin Quelquejay

Valentin Quelquejay

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

More from Medium

Adding SwiftUI view to UIKit project and interacting with it

What is SwiftUI?

SwiftUI Logo

KATLA, wordle-like game with SwiftUI in XCode

SwiftUI: A Better Way To Account For Users Opting For “Reduce Motion”