在iOS 14应用程序生命周期中,有什么方法可以调用SceneDelegate方法?

时间:2020-07-02 12:38:01

标签: ios swift swiftui ios14

我们知道Apple大大简化了SwiftUI应用程序的生命周期(WWDC20)。我看过Paul Hudson先生关于SwiftUI的新变化的视频,其中他解释了如何在“ @main或:App”结构中访问AppDelegate方法。

我想知道是否有任何方法可以访问SceneDelegate方法?

先谢谢了。 :)

2 个答案:

答案 0 :(得分:1)

在SwiftUI 2.0生命周期中,SceneDelegate不再具有访问权限。您可以将.onChange用于 [。active,.inactive,.background] 状态的某些回调,如for example here

或者...继续使用UIKit生命周期没有错

demo

答案 1 :(得分:1)

这是在AppDelegate中访问生命周期的示例。

struct PodcastScene: Scene {
    @Environment(\.scenePhase) private var phase

    var body: some Scene {
        WindowGroup {
            TabView {
                LibraryView()
                DiscoverView()
                SearchView()
            }
        }
        .onChange(of: phase) { newPhase in
            switch newPhase {
            case .active:
                // App became active
            case .inactive:
                // App became inactive
            case .background:
                // App is running in the background
            @unknown default:
                // Fallback for future cases
            }
        }
    }
}

如果添加诸如Firebase之类的框架配置,则可以覆盖init并在此处输入代码。

struct PodcastScene: Scene {

    init() {
        FirebaseApp.configure()
    }

    var body: some Scene {
        WindowGroup {
            TabView {
                LibraryView()
                DiscoverView()
                SearchView()
            }
        }
    }
}