本文介绍了使用 SwiftUI 的新 iOS 14 生命周期访问 AppDelegate 中的 AppState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 iOS 14 中的 SwiftUI 新应用生命周期.

I'm using SwiftUI's new app lifecycle coming in iOS 14.

但是,我在如何访问 AppDelegate 中的 AppState(单一数据源)对象方面遇到了困难.我需要 AppDelegate 在启动时运行代码并注册通知(didFinishLaunchingWithOptionsdidRegisterForRemoteNotificationsWithDeviceTokendidReceiveRemoteNotification)等.

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?

推荐答案

Use shared instance for AppState

Use shared instance for 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 12:43