首页 > 解决方案 > 从 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()
        }
    }
    
}

标签: swiftpush-notificationswiftuiappdelegate

解决方案


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

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

推荐阅读