如何检查iPhone上的通知是否已启用

5

如何检查 iPhone 上的通知是否已启用? 我安装了应用程序,应用程序提示确认为应用程序启用推送通知,我点击确定。但是如果 iPhone 上禁用了通知,则此操作不会启用通知。 如何检查?

2个回答

8

这应该可以工作:

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIRemoteNotificationTypeNone) 
   // Disabled

3
这在iOS8中有所改变。为了支持iOS8及以下版本,请执行以下操作:
+ (BOOL)notificationServicesEnabled {
    BOOL isEnabled = NO;

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){
        UIUserNotificationSettings *notificationSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];

        if (!notificationSettings || (notificationSettings.types == UIUserNotificationTypeNone)) {
            isEnabled = NO;
        } else {
            isEnabled = YES;
        }
    } else {
        UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        if (types & UIRemoteNotificationTypeAlert) {
            isEnabled = YES;
        } else{
            isEnabled = NO;
        }
    }

    return isEnabled;
}

你是把这个放在 AppDelegate 还是 ViewController 中? - SRMR
1
你可以将这段代码放在任何地方,因为它从单例对象中获取数据。就我个人而言,我将代码放在一个DeviceNotificationsManager类中,该类封装了与手机通知子系统相关的逻辑。这样外部世界(即应用程序的其余部分)只需引用DeviceNotificationsManager,而不必详细了解iOS的通知系统。 - Shaheen Ghiassy
嘿@ShaheenGhiassy,上面的代码片段有效。是否有特定的原因来反转if和else部分的逻辑?在if部分,我们检查UIUserNotificationTypeNone,而在else部分,我们检查UIRemoteNotificationTypeAlert。 - iosCurator

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接