Get @EnvironmentObject to NSObject class

263 views Asked by At

I have a simple ObservableObject class which I initialize in the App.swift file and pass to the first view:

final class Counter: ObservableObject {}

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

    private let counter = Counter()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(counter)
        }
    }
}

That works great, but now I need to get at it from my notification delegate. Essentially I have this:

class AppDelegate: NSObject, UIApplicationDelegate {
  let notificationDelegate: NotificationDelegate
  
  func registerForPushNotifications(application: UIApplication) {
    // irrelevant code removed.
    let center = UNUserNotificationCenter.current()
    center.delegate = self?.notificationDelegate
  }
}

class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
}

In my NotificationDelegate class, how do I get access to the Counter class that I instantiated?

1

There are 1 answers

0
Asperi On BEST ANSWER

Here is possible way - to use shared instance (because in your scenario anyway it is used only one instance)

final class Counter: ObservableObject {
   static let shared = Counter()
}

struct MyCoolApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self)
    private var appDelegate

    private let counter = Counter.shared   
    
    // ...
}

...

class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {

  // use in delegate callbacks Counter.shared where needed  

}