使用SwiftUI的新iOS 14生命周期在AppDelegate中访问AppState [英] Accessing AppState in AppDelegate with SwiftUI's new iOS 14 life cycle
问题描述
我正在使用iOS 14中的SwiftUI新应用程序生命周期.
I'm using SwiftUI's new app lifecycle coming in iOS 14.
但是,我被困在如何访问 AppDelegate 中的 AppState (单个事实来源)对象.
我需要 AppDelegate 在启动时运行代码并注册通知(didFinishLaunchingWithOptions
,didRegisterForRemoteNotificationsWithDeviceToken
,didReceiveRemoteNotification
)等.
However, I'm stuck at how to access my AppState (single source of truth) object in the AppDelegate.
I need the AppDelegate to run code on startup and register for notifications (didFinishLaunchingWithOptions
, didRegisterForRemoteNotificationsWithDeviceToken
, didReceiveRemoteNotification
) etc.
我知道@UIApplicationDelegateAdaptor
,但后来我无法使用构造函数将对象传递到 AppDelegate .我想反过来(在 AppDelegate 中创建 AppState ,然后在 MyApp 中访问它)也无法正常工作.
I am aware of @UIApplicationDelegateAdaptor
but then I can not e.g. pass an object through to the AppDelegate with a constructor. I guess the other way round (creating the AppState in the AppDelegate and then accessing it in MyApp) does not work either.
@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生命周期?
Any help is appreciated. Maybe there is currently no way to achieve this, and I need to convert my app to use the old UIKit lifecycle?
推荐答案
将共享实例用于AppState
class AppState: ObservableObject {
static let shared = AppState() // << here !!
// Singe source of truth...
@Published var user = User()
}
因此您可以在任何地方使用它
so you can use it everywhere
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject var appState = AppState.shared
// ... other code
}
和
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// ...and access appState here
AppState.shared.user = ...
}
这篇关于使用SwiftUI的新iOS 14生命周期在AppDelegate中访问AppState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!