我已经在互联网上查看了如何使用IOS 8创建本地通知。我发现了许多文章,但没有解释如何确定用户是否已设置“警报”开启或关闭。请有人帮帮我!!!我更愿意使用Objective C over Swift。
答案 0 :(得分:75)
您可以使用UIApplication
的{{3}}
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");
}
}
希望这有帮助,如果您需要更多信息,请告诉我
答案 1 :(得分:22)
要扩展Albert的答案,您不需要在Swift中使用rawValue
。由于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
}
}
使用括号[]
语法组合选项类型(类似于按位或|
运算符,用于组合其他语言的选项标记)。
答案 2 :(得分:9)
快速与guard
:
guard let settings = UIApplication.sharedApplication().currentUserNotificationSettings() where settings.types != .None else {
return
}
答案 3 :(得分:8)
这是 Swift 3 中的一个简单函数,用于检查是否启用了至少一种类型的通知。
享受!
static func areNotificationsEnabled() -> Bool {
guard let settings = UIApplication.shared.currentUserNotificationSettings else {
return false
}
return settings.types.intersection([.alert, .badge, .sound]).isEmpty != true
}
感谢MichałKałużny的灵感。
答案 4 :(得分:6)
编辑:看看@ simeon的answer。
在Swift中,您需要使用rawValue
:
let grantedSettings = UIApplication.sharedApplication().currentUserNotificationSettings()
if grantedSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 {
// Alert permission granted
}
答案 5 :(得分:2)
使用@simeon答案Xcode告诉我
'currentUserNotificationSettings'在iOS 10.0中已弃用:使用UserNotifications Framework - [UNUserNotificationCenter getNotificationSettingsWithCompletionHandler:]和 - [UNUserNotificationCenter getNotificationCategoriesWithCompletionHandler:]
所以这是使用UNUserNotificationCenter进行 Swift 4 的解决方案:
UNUserNotificationCenter.current().getNotificationSettings(){ (settings) in
switch settings.alertSetting{
case .enabled:
//Permissions are granted
case .disabled:
//Permissions are not granted
case .notSupported:
//The application does not support this notification type
}
}
答案 6 :(得分:0)
Objective C + iOS 10
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
switch (settings.authorizationStatus) {
case UNAuthorizationStatusNotDetermined:
break;
case UNAuthorizationStatusDenied:
break;
case UNAuthorizationStatusAuthorized:
break;
default:
break;
}
}];