【问题标题】:Changing push notification authorization from within a SwiftUI app从 SwiftUI 应用程序中更改推送通知授权
【发布时间】:2020-08-14 23:08:58
【问题描述】:

所以我想让用户能够更改他们的推送通知。我有一个 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()
        }
    }
    
}

【问题讨论】:

    标签: swift push-notification swiftui appdelegate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-11-27
      • 1970-01-01
      • 2012-10-24
      • 2019-09-11
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      相关资源
      最近更新 更多