-1

我有一堂课:

class AppInfos_M: ObservableObject {
    @Published var currentUser: User_M = User_M()
    @Published var userTo: User_M = User_M()
}

我将它从 main 声明为 environmentObject :

...
@main
struct TestApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
...

    @StateObject var appInfos_M = AppInfos_M()
    
    var body: some Scene {
        WindowGroup {
            LaunchScreen_V()
                .environmentObject(appInfos_M)
...
 
        }
    }
}

这门课在我的应用程序中效果很好。现在我需要从 AppDelegate 修改它,因为我需要在收到通知时获取 appInfos_M.userTo.id。我尝试了几件事,但没有一个有效。我怎样才能访问它?

在我需要它的所有观点中,我都以这种方式声明并且它工作正常,但在 AppDelegate 中却不行,为什么?:

 @EnvironmentObject var appInfos_M: AppInfos_M

这是我尝试过的一项无效的测试:

请注意,3 个小点 (...) 用于放置无用代码。

...
class AppDelegate: NSObject, UIApplicationDelegate {...}

...

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
...

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

@EnvironmentObject var appInfos_M: AppInfos_M

 let userInfo = response.notification.request.content.userInfo

appInfos_M.userTo.id = "just for testing here" // <- i get this error : Thread 1: Fatal error: No ObservableObject of type AppInfos_M found. A View.environmentObject(_:) for AppInfos_M may be missing as an ancestor of this view.

...
4

1 回答 1

0

您可以随时存储AppInfos_M在您的AppDelegateLike this

class AppDelegate: NSObject, UIApplicationDelegate {
    var appInfos = AppInfos_M()
    (...)
}

然后,您可以将其用作 EnvironmentObject:

...
@main
struct TestApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
...
    
    var body: some Scene {
        WindowGroup {
            LaunchScreen_V()
                .environmentObject(appDelegate.appInfos)
...
 
        }
    }
}
于 2022-01-23T14:30:08.570 回答