小编Mis*_*r22的帖子

使用 SwiftUI 的新 iOS 14 生命周期访问 AppDelegate 中的 AppState

我正在使用 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)

state appdelegate swift swiftui ios14

7
推荐指数
1
解决办法
2151
查看次数

标签 统计

appdelegate ×1

ios14 ×1

state ×1

swift ×1

swiftui ×1