In the early days of developing apps using UIKit framework, we used UIDelegate to obtain lifecycle callbacks, as follows:

extension AppDelegate: UIApplicationDelegate {
    func applicationDidBecomeActive(_ application: UIApplication) {
        // code here}}Copy the code

Switching to the SwiftUI framework, we handle the lifecycle logic with the SceneDelegate callback:

class SceneDelegate: UIResponder.UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene.willConnectTo session: UISceneSession.options connectionOptions: UIScene.ConnectionOptions) {
        // code here}}Copy the code

But the new Version of XCode no longer offers SceneDelegate, and the main entry point for the entire application is reduced to an App protocol:

import SwiftUI

@main
struct iOS_testApp: App {
    var body: some Scene {
        WindowGroup {
            Text("hello, iOS_testApp.")}}}Copy the code

Under the new framework, if there is a need to monitor the life cycle for code processing, the scenePhase variable in @Environment should be used to complete the monitoring. The specific code is as follows:

import SwiftUI

@main
struct iOS_testApp: App {
    @Environment(\.scenePhase) private var scenePhase
    var body: some Scene {
        WindowGroup {
            Text("hello, iOS_testApp.")
        }
        .onChange(of: scenePhase) { newScenePhase in
            switch newScenePhase {
            case .active :
                print("App active")
            case .inactive :
                print("App inactive")
            case .background :
                print("App background")
            @unknown default :
                print("Others")}}}}Copy the code

Friends who want to discuss together can apply for adding group in the group menu bar of my public account Fenghai Causeway to complete adding group application, and make progress together.