ScenePhase Environment Variable in SwiftUI

DevTechie Inc
May 11, 2023

SwiftUI app moves from various phases of lifecycle and knowing about those phases can be helpful to make important decisions. ScenePhase enum gives us access to three important phases of app lifecycle, activeinactive, and background.

We can access ScenePhase via Environment variable and observe the change in scene to act accordingly.

Bank or financial apps often hide the app UI when app either goes inactiveor in background. In this article, we will mimic the same case. When the app is in inactive or background state, we will show DevTechie logo on screen otherwise we will show a list.

We will start by querying Environment variable. Environment variable has a key path called “scenePhase” which gives us access to all scene phases.

@Environment(\.scenePhase) private var scenePhase

We will create two computed property for views for active and inactivestates

var activeState: some View {
        NavigationStack {
            VStack {
                List {
                    ForEach(0..<50) { idx in
                        Text("This is idx\(idx)")
                    }
                }
            }
            .navigationTitle("DevTechie")
        }
    }
    
    var inactiveState: some View {
        Image("DT")
    }

Inside the body of main view, we will use conditional statement to show these active and inactive views based on the scenePhase value. Complete code should look like this

struct DevTechieScenePhase: View {
    @Environment(\.scenePhase) private var scenePhase
    
    var body: some View {
        if scenePhase == .background || scenePhase == .inactive {
            inactiveState
        } else {
            activeState
        }
    }
    
    var activeState: some View {
        NavigationStack {
            VStack {
                List {
                    ForEach(0..<50) { idx in
                        Text("This is idx\(idx)")
                    }
                }
            }
            .navigationTitle("DevTechie")
        }
    }
    
    var inactiveState: some View {
        Image("DT")
    }
}