I implemented the three callback functions inside the AppDelegate class as suggested in the Register Your App and Retrieve Your App's Device Token example. The didRegisterForRemoteNotificationsWithDeviceToken() calls the self.sendDeviceTokenToServer(data: deviceToken) assuming that this method is within the AppDelegate class. However, I prefer sendDeviceTokenToServer() to belong to a different class. However, the following implementation has a runtime error: "Fatal Error: No ObservableObject of type Client found":
import SwiftUI
@main
struct app1App: App {
var client : Client = Client()
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
MainView().environmentObject(client)
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
@EnvironmentObject var client : Client
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken
deviceToken: Data) {
client.sendDeviceTokenToServer(token : deviceToken) // <<<----- this is where it crashes
}
}
Any ideas how to fix this problem? The views inside the MainView have no problem accessing the methods and properties of the client object.
CodePudding user response:
@EnvironmentObject
is only for a SwiftUIView
it does not work in aclass
@EnvironmentObject
has to be injected in the parentView
theAppDelegate
has no way of knowing about it.One approach is to have the
AppDelegate
own theclient
and then make is available to the subviews of theapp1App
Remove from app1App
var client : Client = Client()
Then change the AppDelegate
class AppDelegate: NSObject, UIApplicationDelegate {
let client : Client = Client()
//the rest of the delegate
}
Then inject the client
to the subviews by replacing
MainView().environmentObject(client)
With
MainView().environmentObject(appDelegate.client)
The client
will be available by appDelegate.client
This of course assumes the the client
is an ObservableObject