我正在使用 iOS 14 中推出的 SwiftUI 新应用程序生命周期。
但是,我不知道如何访问我的AppState(单一事实来源)对象应用程序代理。
我需要应用程序代理在启动时运行代码并注册通知(didFinishLaunchingWithOptions
, didRegisterForRemoteNotificationsWithDeviceToken
, didReceiveRemoteNotification
) etc.
我知道@UIApplicationDelegateAdaptor
但我不能例如将一个对象传递给应用程序代理与构造函数。我想反过来(创建AppState in the 应用程序代理然后访问它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 生命周期?