'How to access AppDelegate object and call method from other SwiftUI views

I am working with the SwiftUI app and I configured my Push Notification setup in AppDelegate and it's working fine like below:

Messaging.messaging().delegate = self

        if #available(iOS 10.0, *) {
          // For iOS 10 display notification (sent via APNS)
          UNUserNotificationCenter.current().delegate = self

          let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
          UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
        } else {
          let settings: UIUserNotificationSettings =
          UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
          application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

Now I have to move this code from app launch to TabBarView screen where I can request for permission once login success.

So for that, I have created func in AppDelegate file like this:

func enablePushNotification() {
        
        let application = UIApplication.shared

        if #available(iOS 10.0, *) {
          // For iOS 10 display notification (sent via APNS)
          UNUserNotificationCenter.current().delegate = self

          let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
          UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
        } else {
          let settings: UIUserNotificationSettings =
          UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
          application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
    }

and calling it from TabBarView() like this:

init() {
        print("TabBar Init called")
        configurePushNotification()
    }

func configurePushNotification() {
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            appDelegate.enablePushNotification()
        }
    }

But I am not able to get the AppDelegate object here and It's unable to call appDelegate method from TabBarView().

Any suggestion here why I am not able to get the AppDelegate object or is there any other way to get it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source