我们知道Apple大大简化了SwiftUI应用程序的生命周期(WWDC20)。我看过Paul Hudson先生关于SwiftUI的新变化的视频,其中他解释了如何在“ @main或:App”结构中访问AppDelegate方法。
我想知道是否有任何方法可以访问SceneDelegate方法?
先谢谢了。 :)
答案 0 :(得分:1)
在SwiftUI 2.0生命周期中,SceneDelegate
不再具有访问权限。您可以将.onChange
用于 [。active,.inactive,.background] 状态的某些回调,如for example here
或者...继续使用UIKit生命周期没有错
答案 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()
}
}
}
}