如何在请求权限后检查UNNotifications是否已启用?
问题描述:
目前,我有下面的代码,基本上是要求用户许可发送通知,然后检查是否启用通知:如何在请求权限后检查UNNotifications是否已启用?
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
if granted {
} else {
}
})
let notifType = UIApplication.shared.currentUserNotificationSettings?.types
if notifType?.rawValue == 0 {
print("being called")
let alert = UIAlertController(title: "Notifications are disabled for this app.", message: "Please enable notifications for the app to work properly. This can be done by going to Settings > Notifications > NAME HERE and allow notifications.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
show(alert, sender: self)
} else {
//enabled
}
代码工作,如果启用通知然而,它检查然后用户可以选择“是”或“否”。因此,无论选择什么,弹出对话框。有没有一种方法可以等待用户选择“是”还是“否”之前检查授权状态?
答
您可以将检查到的回调,所以授权首先检查:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
if (granted) {
// Alert here
} else {
// Or here
}
})
哇,这是一个简单的办法,谢谢! –