美文网首页
2021新版XCode下SwiftUI的App生命周期监控新方案

2021新版XCode下SwiftUI的App生命周期监控新方案

作者: 风海铜锣君 | 来源:发表于2021-07-14 10:29 被阅读0次

早期在使用UIKit框架开发App时,我们通过UIDelegate来获得生命周期回调,具体如下:

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

后来换用SwiftUI框架,我们通过SceneDelegate回调来处理生命周期逻辑:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

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

但是新版XCode不再提供SceneDelegate,整个应用程序的主入口简化为一个App协议:

import SwiftUI

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

在新的框架下,如果还有监控生命周期进行代码处理的需求,就要用到@Environment中的scenePhase变量来完成监控,具体代码如下:

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")
            }
        }
    }
}

想要一起讨论的朋友可以在我的公众号风海铜锣的加群菜单栏中申请加群完成加群申请,一起共同进步。

相关文章

网友评论

      本文标题:2021新版XCode下SwiftUI的App生命周期监控新方案

      本文链接:https://www.haomeiwen.com/subject/phfypltx.html