请求许可后,如何检查是否启用了 UNNotifications?

How to check if UNNotifications are enabled, after asking for permission?

目前我有以下代码,本质上是询问用户发送通知的权限,然后检查是否启用了通知:

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
    }

该代码有效,但是,它会在用户 select "yes" 或 "no" 之前检查通知是否已启用。这样,无论输入什么select,都会弹出对话框。有没有办法等到用户 selects "yes" 或 "no"?

时才检查授权状态

您可以将检查移到回调中,因此首先检查授权:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
    if (granted) {
        // Alert here
    } else {
       // Or here
    }
})