如何检查 iOS 应用程序的通知状态
无论你的应用程序是否在用户的设备上运行,通知都会向用户传达重要信息。
例如,一个体育应用程序可以告诉用户,当他们的喜爱球队得分时候。通知还可以告诉你的应用程序下载信息并更新其界面。通知可以显示提醒、播放声音或给该应用程序的图标添加徽章。
你可以在这里https://developer.apple.com/documentation/usernotifications 更多地了解通知的状态
Apple 建议用户使用 UserNotifications 框架,那么我们开始吧。我们将看到一个非常简单而轻松的解决方案来获取通知状态。
步骤 1 − 首先,你需要导入 UserNotifications 框架
import UserNotifications
步骤2 − 创建一个 UNUserNotificationCenter.current() 对象
let currentNotification = UNUserNotificationCenter.current()
步骤 3 − 检查状态
currentNotification.getNotificationSettings(completionHandler: { (settings) in if settings.authorizationStatus == .notDetermined { // Notification permission is yet to be been asked go for it! } else if settings.authorizationStatus == .denied { // Notification permission was denied previously, go to settings & privacy to re-enable the permission } else if settings.authorizationStatus == .authorized { // Notification permission already granted. } })
最终代码
import UserNotifications let currentNotification = UNUserNotificationCenter.current() currentNotification.getNotificationSettings(completionHandler: { (settings) in if settings.authorizationStatus == .notDetermined { // Notification permission is yet to be been asked go for it! } else if settings.authorizationStatus == .denied { // Notification permission was denied previously, go to settings & privacy to re-enable the permission } else if settings.authorizationStatus == .authorized { // Notification permission already granted. } })
广告