nickcoding
nickcoding

Reputation: 475

Changing push notification authorization from within a SwiftUI app

So I'd like to give the user the ability to change their push notifications. I have a registerForPushNotifications() function that is called when the user first opens the app in AppDelegate. I figure if I can access these same functions from a view when a button is pressed or a toggle is changed, I can just trigger the authorization popup again. I just am not sure how to access the function in AppDelegate from ContentView.

func registerForPushNotifications() {
    UNUserNotificationCenter.current()
      .requestAuthorization(options: [.alert, .sound, .badge]) {
        [weak self] granted, error in
        
        print("Permission granted: \(granted)")
        guard granted else { return }
        self?.getNotificationSettings()
    }
}

func getNotificationSettings() {
    UNUserNotificationCenter.current().getNotificationSettings { settings in
        print("Notification settings: \(settings)")
        guard settings.authorizationStatus == .authorized else { return }
        DispatchQueue.main.async {
          UIApplication.shared.registerForRemoteNotifications()
        }
    }
    
}

Upvotes: 1

Views: 1480

Answers (1)

Asperi
Asperi

Reputation: 257583

You can extract those functions into standalone helper class like

class RegistrationHelper {
    static let shared = RegistrationHelper()

    func registerForPushNotifications() {
        UNUserNotificationCenter.current()
            .requestAuthorization(options: [.alert, .sound, .badge]) {
                [weak self] granted, error in

                print("Permission granted: \(granted)")
                guard granted else { return }
                self?.getNotificationSettings()
            }
    }

    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }

    }
}

and use/call it in any places as

RegistrationHelper.shared.registerForPushNotifications()

Upvotes: 1

Related Questions