我正在使用 iOS 14 中 SwiftUI 的新应用程序生命周期。
但是,我被困在如何在AppDelegate 中访问我的AppState(单一事实来源)对象。我需要的AppDelegate在启动时运行的代码,并注册通知(,,)等等。didFinishLaunchingWithOptionsdidRegisterForRemoteNotificationsWithDeviceTokendidReceiveRemoteNotification
我知道@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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// access appState here...
return …Run Code Online (Sandbox Code Playgroud)