检查IOS 8中是否启用了本地通知

Jac*_*man 30 notifications localnotification ios8

我已经在互联网上查看了如何使用IOS 8创建本地通知.我发现了许多文章,但没有解释如何确定用户是否已设置"警报"开启或关闭.请有人帮帮我!!! 我更喜欢使用Objective C over Swift.

Bhu*_*hta 75

您可以通过检查它UIApplicationcurrentUserNotificationSettings

if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){ // Check it's iOS 8 and above
    UIUserNotificationSettings *grantedSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];

    if (grantedSettings.types == UIUserNotificationTypeNone) {
        NSLog(@"No permiossion granted");
    }
    else if (grantedSettings.types & UIUserNotificationTypeSound & UIUserNotificationTypeAlert ){
        NSLog(@"Sound and alert permissions ");
    }
    else if (grantedSettings.types  & UIUserNotificationTypeAlert){
        NSLog(@"Alert Permission Granted");
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这有帮助,如果您需要更多信息,请告诉我

  • 这很棒.如果用户先前拒绝了权限,则键入== none,但再次询问它不会显示请求窗口.我怎么知道他们以前是否否认过它?如果我已经问过,我应该在用户偏好中保留一个标志吗? (6认同)

sim*_*eon 22

要扩展Albert的答案,您不需要rawValue在Swift中使用.因为UIUserNotificationType符合OptionSetType它可以执行以下操作:

if let settings = UIApplication.shared.currentUserNotificationSettings {
    if settings.types.contains([.alert, .sound]) {
        //Have alert and sound permissions
    } else if settings.types.contains(.alert) {
        //Have alert permission
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用括号[]语法来组合选项类型(类似于|用于组合其他语言中的选项标志的按位或运算符).

  • 你的答案是最好的答案Michal Kaluzny +1 (2认同)

zgj*_*jie 9

斯威夫特guard:

guard let settings = UIApplication.sharedApplication().currentUserNotificationSettings() where settings.types != .None else {
    return
}
Run Code Online (Sandbox Code Playgroud)


dus*_*rwh 9

这是Swift 3中的一个简单函数,用于检查是否启用了至少一种类型的通知.

请享用!

static func areNotificationsEnabled() -> Bool {
    guard let settings = UIApplication.shared.currentUserNotificationSettings else {
        return false
    }

    return settings.types.intersection([.alert, .badge, .sound]).isEmpty != true
}
Run Code Online (Sandbox Code Playgroud)

感谢MichałKałużny的灵感.


Alb*_*lvo 6

编辑:看看@ simeon的回答.

在Swift中,您需要使用rawValue:

let grantedSettings = UIApplication.sharedApplication().currentUserNotificationSettings()
if grantedSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 {
    // Alert permission granted
} 
Run Code Online (Sandbox Code Playgroud)

  • 不要使用`rawValue,我认为没有任何保证他们永远不会改变.正如@simeon所说,使用`settings.types.contains(.Alert)` (3认同)