Home > Net >  Call external method from AppDelegate swiftui
Call external method from AppDelegate swiftui

Time:06-28

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:

  1. @EnvironmentObject is only for a SwiftUI View it does not work in a class

  2. @EnvironmentObject has to be injected in the parent View the AppDelegate has no way of knowing about it.

  3. One approach is to have the AppDelegate own the client and then make is available to the subviews of the app1App

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

  • Related