在SwiftUI应用中更改推送通知授权

问题描述

因此,我想让用户能够更改其推送通知我有一个registerForPushNotifications()函数,当用户首次在AppDelegate中打开应用程序时会调用函数。我认为如果按下按钮或更改切换后是否可以从视图访问这些相同的功能,我可以再次触发授权弹出窗口。我只是不确定如何从ContentView访问AppDelegate中的功能

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()
        }
    }
    
}

解决方法

您可以将这些函数提取到独立的帮助器类中,例如

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()
            }
        }

    }
}

并在任何地方使用/调用它

RegistrationHelper.shared.registerForPushNotifications()