oh-my-docs

Summary for developers


Project maintained by italkso Hosted on GitHub Pages — Theme by mattgraham

应用生命周期

The current state of your app determines what it can and cannot do at any time. For example, a foreground app has the user’s attention, so it has priority over system resources, including the CPU. By contrast, a background app must do as little work as possible, and preferably nothing, because it is offscreen. As your app changes from state to state, you must adjust its behavior accordingly.

Managing Your App’s Life Cycle - Apple Developer

App Life Cycle

五种状态

应用的生命周期 (App Life Cycle)是指应用程序在设备上运行时的不同状态。当用户对应用进行不同的操作时,应用会在用户进行不同操作时在这些状态中进行切换

项目实践

import SiwftUI

@main
struct ForCreatorLifeCycleApp: App {
    @environment(\.scenePhase) private var scenePhase
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase) { newPhase in 
        	switch newPhase {
                case .active:
                	print("Foreground Active")
                case .inactive:
                	print("Foreground Inactive")
                case .background:
                	print("Background")
                @unknown default:
                	print("Error")
            }            
        }
    }
}