This is the first post! I was developing an iOS app with SwiftUI, and I had a hard time finding out how to get the launch status of the app, so I will share it here as a memorandum.
The startup state of the iOS app can be divided into three states: Active, Inactive, and Background. The state transition diagram is as shown in the figure below. You can see that when you start it, it goes through Inactive and then becomes Active, and when it goes from Active to Background, it goes through Inactive.
See Apple Official Documentation for more information.
Until recently, Swift UI did not have an API to get the startup status of the app, but from iOS14 it can be easily obtained by using Scene Phase .
Specifically, you can get it by adding the following property to the App instance.
@Environment(\.scenePhase) private var scenePhase
Let's look at an example. Rewrite TestApp.swift, which is automatically generated when you launch a new project in Xcode, as follows. (In this case, Test is the project name)
//
// TestApp.swift
// Test
//
// Created by Ossamoon on 2020/12/25.
//
import SwiftUI
@main
struct TestApp: App {
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
ContentView()
}
.onChange(of: scenePhase) { phase in
switch phase {
case .background:
print ("Background")
case .active:
print ("active")
case .inactive:
print ("inactive")
default:
print ("Something is strange if this message appears")
}
}
}
}
Let's start the app in the simulator. Then, the message "Active" appears on the console.
If you swipe from here to display the menu, the message "Inactive" will appear.
If you go to another screen, the message "Background" will appear.
If you return to the app screen again, the message "Inactive" will be displayed, followed by the message "Inactive".
It behaves like this. I hope you can actually play around with it at your fingertips.
You can see that you can easily get the launch status of the app by using ScenePhase.
There is a restriction that it can be used only with iOS 14 or later, but it is a very convenient API, so please try Scene Phase!
Recommended Posts