【发布时间】:2020-12-15 06:18:21
【问题描述】:
我正在使用 iOS 14 中即将推出的 SwiftUI 新应用生命周期。
但是,我不知道如何在 AppDelegate 中访问我的 AppState(单一事实来源)对象。
我需要 AppDelegate 在启动时运行代码并注册通知(didFinishLaunchingWithOptions、didRegisterForRemoteNotificationsWithDeviceToken、didReceiveRemoteNotification)等。
我知道@UIApplicationDelegateAdaptor 但是我不能,例如使用构造函数将对象传递给 AppDelegate。我猜反过来(在 AppDelegate 中创建 AppState 然后在 MyApp 中访问它)也不起作用。
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@State var appState = AppState()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(appState)
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// access appState here...
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// ...and access appState here
}
}
class AppState: ObservableObject {
// Singe source of truth...
@Published var user: User()
}
感谢任何帮助。也许目前没有办法实现这一点,我需要将我的应用程序转换为使用旧的 UIKit 生命周期?
【问题讨论】:
标签: swift swiftui state appdelegate ios14