从 SwiftUI 应用程序中更改推送通知授权
Posted
技术标签:
【中文标题】从 SwiftUI 应用程序中更改推送通知授权【英文标题】:Changing push notification authorization from within a SwiftUI app 【发布时间】: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()
【问题讨论】:
【参考方案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()
【讨论】:
以上是关于从 SwiftUI 应用程序中更改推送通知授权的主要内容,如果未能解决你的问题,请参考以下文章
Google 推送通知 - 未经授权的 WebHook 回调通道
没有 AppDelegate 的 SwiftUI 远程推送通知 - 有可能吗?