Я просмотрел по всему Интернету, как создавать локальные уведомления с IOS 8. Я нашел много статей, но ни один из них не объяснил, как определить, включен ли пользователь "оповещения". Может кто-нибудь, пожалуйста, помогите мне!!! Я бы предпочел использовать Objective C поверх Swift.
Проверьте, включены ли локальные уведомления в IOS 8
Ответ 1
Вы можете проверить это, используя UIApplication
currentUserNotificationSettings
if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){ // Check it 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");
}
}
Надеюсь, что это поможет, дайте мне знать, если вам нужна дополнительная информация
Ответ 2
Чтобы расширить ответ Альберта, вы не обязаны использовать 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
}
}
Вы используете синтаксис []
для объединения типов опций (аналогично оператору bitwise или |
для объединения флагов опций на других языках).
Ответ 3
Swift с guard
:
guard let settings = UIApplication.sharedApplication().currentUserNotificationSettings() where settings.types != .None else {
return
}
Ответ 4
Вот простая функция в 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 за вдохновение.
Ответ 5
Изменить: Посмотрите на @simeon ответ.
В Swift вам нужно использовать rawValue
:
let grantedSettings = UIApplication.sharedApplication().currentUserNotificationSettings()
if grantedSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 {
// Alert permission granted
}
Ответ 6
Я думаю, что этот код более точный:
if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]) {
UIUserNotificationType types = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
if (types & UIUserNotificationTypeBadge) {
NSLog(@"Badge permission");
}
if (types & UIUserNotificationTypeSound){
NSLog(@"Sound permission");
}
if (types & UIUserNotificationTypeAlert){
NSLog(@"Alert permission");
}
}