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

Mis*_*r22 7 state appdelegate swift swiftui ios14

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

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // ...and access appState here
    }
}
Run Code Online (Sandbox Code Playgroud)
class AppState: ObservableObject {
    // Singe source of truth...
    @Published var user: User()
}
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。也许目前没有办法实现这一点,我需要将我的应用程序转换为使用旧的 UIKit 生命周期?

Asp*_*eri 11

使用共享实例 AppState

class AppState: ObservableObject {
    static let shared = AppState()    // << here !!

    // Singe source of truth...
    @Published var user = User()
}
Run Code Online (Sandbox Code Playgroud)

所以你可以在任何地方使用它

struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    @StateObject var appState = AppState.shared

    // ... other code
}
Run Code Online (Sandbox Code Playgroud)

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // ...and access appState here

        AppState.shared.user = ...
    }
Run Code Online (Sandbox Code Playgroud)

  • 是的,SwiftUI 2.0 StateObject 正是用于此目的。 (3认同)