Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use my @EnvironmentObject in AppDelegate in SwiftUi (iOS 15 / Xcode 13.2.1)?

I have a class :

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

I declare it in main and pass in to my view with 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)
...
 
        }
    }
}

The class works very good in my app. Now I need to modify it from AppDelegate, because I need to get appInfos_M.userTo.id when I get a notification. I tried several things, but none works. How can I access it?

In all my views where I need it, I declare this way and it works fine, but not in AppDelegate, why?:

 @EnvironmentObject var appInfos_M: AppInfos_M

Here is one of the tests I tried that did not work:

...

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.

...

Note that 3 small dots ... replace any code that is useless here.

like image 409
Flincorp Avatar asked Nov 03 '25 07:11

Flincorp


1 Answers

You can always store AppInfos_M in your AppDelegate Like this

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

You can then use it as EnvironmentObject as:

...
@main
struct TestApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
...
    
    var body: some Scene {
        WindowGroup {
            LaunchScreen_V()
                .environmentObject(appDelegate.appInfos)
...
 
        }
    }
}
like image 185
cluelessCoder Avatar answered Nov 06 '25 01:11

cluelessCoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!