swift - 从 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()
推荐阅读
- compiler-errors - gfortran:-fimplicit-none 不绕过错误
- python - 将多列连接成新列。csv 文件,python,熊猫
- python - 使用 SQLAlchemy 批量插入 Azure SQL 不持久
- android - Android 8.1 连接到调用 connectGatt 的 BLE 外围设备。回调总是说断开连接。从不连接
- javascript - 使用 Cheerio Nodejs 进行网页抓取
- php - 如何在php中显示当前日期和200天+当前日期
- json - 如何在 web api 控制器中访问微服务的域模型
- groovy - 如何在 RxGroovy 中使用响应式 .groupBy
- angular - Angular 在哪里存储全局数据?
- tensorflow - 用 keras 编写的神经网络的超参数优化