scenePhase not behaving as expected on screen lock

Seeing weird sequences of changes when locking the screen when view is visable.

.onChange(of: scenePhase) { phase in
if phase == .active {
if UIApplication.shared.applicationState == .active {
print("KDEBUG: App genuinely became active")
} else {
print("KDEBUG: False active signal detected")
}
} else if phase == .inactive {
print("KDEBUG: App became inactive")
// Handle inactive state if needed
} else if phase == .background {
print("KDEBUG: App went to background")
// Handle background state if needed
}
}

seen:

(locks screen)

KDEBUG: App became inactive
KDEBUG: App genuinely became active
KDEBUG: App went to background

expected

(locks screen)

KDEBUG: App became inactive
KDEBUG: App went to background

Coupe of things here.

I'll assume you've set scenePhase using:

@Environment(\.scenePhase) private var scenePhase

If so, you don't need phase in; you can simply refer to scenePhase, i.e.:

.onChange(of: scenePhase) {
if(scenePhase == .active) {

Secondly, scenePhase does not equal UIApplication.shared.applicationState. An application can be active and a scene can be inactive. That's why you're seeing your debug output.

The app goes into the background after a few seconds, to allow you to complete any processing you needed to do - writing to a file, or database, whatever. The scene will go into the background before the app.

Do you really need to know if the app state has changed, or the scene? It seems you're mixing two things here.

To add to the point mentioned, UIApplication.shared.applicationState applies to the entire application and doesn't distinguish between multiple scenes or windows.

while scene acts as a container for a view hierarchy that you want to display to the user.

in iOS 13, multi-scene support introduced and allow you track separate life-cycle events for each scene.

SceneAPI documentation covers what you need to know and you can also review Managing your app’s life cycle and Managing your app’s life cycle for more information on handling scene-based life cycle events.

scenePhase not behaving as expected on screen lock
 
 
Q