检查推送通知注册:isRegisteredForRemoteNotifications 不更新

17
以下方法一直返回相同的值:
[[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
每次运行此代码,结果都是“YES”。即使我进入“设置”应用程序并将我的应用程序的推送通知设置为“关闭”,当上述代码运行时,它仍然计算为“YES”。
其他细节: * 我正在一个运行iOS 8.1.3的iPhone上运行该应用程序 * 我正在Xcode 6.1中运行该应用程序,并将手机与我的机器物理连接
有任何想法为什么“isRegisteredForRemoteNotifications”的值不会改变吗?

1
可能是detect "Allow Notifications" is on/off for iOS8的重复问题 - 请查看建议使用currentUserNotificationSettings的答案。 - Aaron Brager
大多数答案错误地建议检查 isRegisteredForRemoteNotifications。@AaronBrager - Lefteris
2个回答

21

iOS 8即使用户选择退出推送通知,也会注册设备并提供令牌。

在这种情况下,当推送消息发送时不会向用户呈现,但如果您的应用正在运行,则会收到负载,因此您可以在应用运行时进行更新...

要检查iOS 8中是否启用了推送通知,应检查已启用的用户通知类型:

- (BOOL)pushNotificationsEnabled {
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]) {
        UIUserNotificationType types = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
        return (types & UIUserNotificationTypeAlert);
    }
    else {
        UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        return (types & UIRemoteNotificationTypeAlert);
    }
}

1
如果您正在使用Swift 2,按位运算符将无法与UIUserNotificationType一起使用。以下是使用Swift 2、iOS 8+的解决方案:
func hasPushEnabled() -> Bool {
        //ios 8+
        if UIApplication.sharedApplication().respondsToSelector("currentUserNotificationSettings") == true {
            let settings = UIApplication.sharedApplication().currentUserNotificationSettings()
            if (settings?.types.contains(.Alert) == true){
                return true
            }
            else {
                return false
            }
        }
        else {
            let types = UIApplication.sharedApplication().enabledRemoteNotificationTypes()
            if types.contains(.Alert) == true {
                return true
            }
            else {
                return false
            }
}

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