Detect when your app is sent to the background or foreground in SwiftUI


Greetings, traveler!

We can change our app’s behavior based on its current state. We can do this in UIKit and SwiftUI. This article will describe a SwiftUI way of app phase monitoring.

Note

By the way, if you want to learn how to do this via UIKit, you can check out this article.

UIApplication

We can use this method to observe the app’s state changes. Consider this example:

struct ContentView: View {
    
    @Environment(\.scenePhase) var scenePhase
    
    var body: some View {
        Text("Text")
            .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
                // do something...
            }
    }
    
}

scenePhase

Another way to do this is by using the Environment scenePhase key to observe the current phase of the scene. Check out this code:

struct ContentView: View {
    
    @Environment(\.scenePhase) var scenePhase
    
    var body: some View {
        Text("Text")
            .onChange(of: scenePhase) { _, newValue in
                switch newValue {
                case .background:
                    print("background")
                case .inactive:
                    print("inactive")
                case .active:
                    print("active")
                @unknown default:
                    break
                }
            }
    }
    
}

What do these cases mean?

  • Active: The scene is in the foreground and interactive.
  • Inactive: The scene is in the foreground but should pause its work.
  • Background: The scene isn’t currently visible in the UI.

Conclusion

As you can see, everything is simple. We can use these tools to control our app’s behavior.