Determinar en el iPhone si el usuario ha habilitado las notificaciones push
Estoy buscando una manera de determinar si el usuario, a través de la configuración, ha habilitado o deshabilitado sus notificaciones push para mi aplicación.
19 answers
Llama a enabledRemoteNotificationsTypes
y comprueba la máscara.
Por ejemplo:
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIRemoteNotificationTypeNone)
// blah blah blah
IOS8 y superior:
[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-19 13:29:05
No puedo comentar (no hay suficiente reputación), pero re: cuestión de quantumpotato:
Donde types
viene dado por
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
Se puede usar
if (types & UIRemoteNotificationTypeAlert)
En lugar de
if (types == UIRemoteNotificationTypeNone)
Le permitirá verificar solo si las notificaciones están habilitadas (y no se preocupe por los sonidos, las insignias, el centro de notificaciones, etc.). La primera línea de código (types & UIRemoteNotificationTypeAlert
) devolverá YES
si "Alert Style" se establece en "Banners" o "Alerts", y NO
si " Alert Style "se establece en "None", independientemente de otros configuración.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-15 16:23:24
En la última versión de iOS, este método está obsoleto. Para soportar iOS 7 e iOS 8 use:
UIApplication *application = [UIApplication sharedApplication];
BOOL enabled;
// Try to use the newer isRegisteredForRemoteNotifications otherwise use the enabledRemoteNotificationTypes.
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
enabled = [application isRegisteredForRemoteNotifications];
}
else
{
UIRemoteNotificationType types = [application enabledRemoteNotificationTypes];
enabled = types & UIRemoteNotificationTypeAlert;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-19 23:53:52
Código actualizado para swift4. 0 , iOS11
import UserNotifications
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
//Not authorised
UIApplication.shared.registerForRemoteNotifications()
}
Código para swift3. 0 , iOS10
let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
if isRegisteredForRemoteNotifications {
// User is registered for notification
} else {
// Show alert user is not registered for notification
}
Desde iOS9, swift 2.0 UIRemoteNotificationType está obsoleto, use el siguiente código
let notificationType = UIApplication.shared.currentUserNotificationSettings!.types
if notificationType == UIUserNotificationType.none {
// Push notifications are disabled in setting by user.
}else{
// Push notifications are enabled in setting by user.
}
Simplemente compruebe si las notificaciones push están habilitadas
if notificationType == UIUserNotificationType.badge {
// the application may badge its icon upon a notification being received
}
if notificationType == UIUserNotificationType.sound {
// the application may play a sound upon a notification being received
}
if notificationType == UIUserNotificationType.alert {
// the application may display an alert upon a notification being received
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-15 08:02:51
A continuación encontrará un ejemplo completo que cubre tanto iOS8 como iOS7 (y versiones inferiores). Tenga en cuenta que antes de iOS8 no se puede distinguir entre "notificaciones remotas desactivadas" y "solo Ver en pantalla de bloqueo habilitado".
BOOL remoteNotificationsEnabled = false, noneEnabled,alertsEnabled, badgesEnabled, soundsEnabled;
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// iOS8+
remoteNotificationsEnabled = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;
UIUserNotificationSettings *userNotificationSettings = [UIApplication sharedApplication].currentUserNotificationSettings;
noneEnabled = userNotificationSettings.types == UIUserNotificationTypeNone;
alertsEnabled = userNotificationSettings.types & UIUserNotificationTypeAlert;
badgesEnabled = userNotificationSettings.types & UIUserNotificationTypeBadge;
soundsEnabled = userNotificationSettings.types & UIUserNotificationTypeSound;
} else {
// iOS7 and below
UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;
noneEnabled = enabledRemoteNotificationTypes == UIRemoteNotificationTypeNone;
alertsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeAlert;
badgesEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeBadge;
soundsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeSound;
}
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
NSLog(@"Remote notifications enabled: %@", remoteNotificationsEnabled ? @"YES" : @"NO");
}
NSLog(@"Notification type status:");
NSLog(@" None: %@", noneEnabled ? @"enabled" : @"disabled");
NSLog(@" Alerts: %@", alertsEnabled ? @"enabled" : @"disabled");
NSLog(@" Badges: %@", badgesEnabled ? @"enabled" : @"disabled");
NSLog(@" Sounds: %@", soundsEnabled ? @"enabled" : @"disabled");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-28 07:01:05
Swift 3+
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
// settings.authorizationStatus == .authorized
})
} else {
return UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert) ?? false
}
RxSwift Versión observable para iOS10+:
import UserNotifications
extension UNUserNotificationCenter {
static var isAuthorized: Observable<Bool> {
return Observable.create { observer in
DispatchQueue.main.async {
current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
if settings.authorizationStatus == .authorized {
observer.onNext(true)
observer.onCompleted()
} else {
current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
observer.onNext(granted)
observer.onCompleted()
}
}
})
}
return Disposables.create()
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-08 11:05:46
Al intentar soportar tanto iOS8 como inferiores, no tuve mucha suerte usando isRegisteredForRemoteNotifications
como Kevin sugirió. En su lugar usé currentUserNotificationSettings
, que funcionó muy bien en mis pruebas.
+ (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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-05 11:00:36
Desafortunadamente ninguna de estas soluciones proporcionadas realmente resuelven el problema porque al final del día las API carecen seriamente a la hora de proporcionar la información pertinente. Sin embargo, puede hacer algunas conjeturas usando currentUserNotificationSettings
(iOS8+) simplemente no es suficiente en su forma actual para responder realmente a la pregunta. Aunque muchas de las soluciones aquí parecen sugerir que eso o isRegisteredForRemoteNotifications
es más una respuesta definitiva, realmente no lo es.
Considere esto:
Con isRegisteredForRemoteNotifications
la documentación establece:
Devuelve SÍ si la aplicación está registrada actualmente para notificaciones remotas, teniendo en cuenta cualquier configuración de todo el sistema...
Sin embargo, si lanzas un simple NSLog
en tu delegado de aplicación para observar el comportamiento, está claro que esto no se comporta de la manera en que anticipamos que funcionará. En realidad, se refiere directamente a las notificaciones remotas que se han activado para esta aplicación/dispositivo. Una vez activado para la primera vez esto siempre volverá YES
. Incluso apagarlos en la configuración (notificaciones) todavía resultará en este retorno YES
esto se debe a que, a partir de iOS8, una aplicación puede registrarse para notificaciones remotas e incluso enviar a un dispositivo sin que el usuario tenga notificaciones habilitadas, simplemente no pueden hacer Alertas, Insignias y Sonido sin que el usuario lo active. Las notificaciones silenciosas son un buen ejemplo de algo que puede seguir haciendo incluso con las notificaciones desactivadas.
Hasta ahora como currentUserNotificationSettings
indica una de cuatro cosas:
Las alertas están activadas Las insignias están encendidas El sonido está encendido Ninguno está encendido.
Esto no le da absolutamente ninguna indicación sobre los otros factores o el cambio de Notificación en sí.
De hecho, un usuario puede desactivar las insignias, el sonido y las alertas, pero aún así mostrar en la pantalla de bloqueo o en el centro de notificaciones. Este usuario debería seguir recibiendo notificaciones push y poder verlas tanto en la pantalla de bloqueo como en el centro de notificaciones. Le tenga el interruptor de notificación encendido. PERO currentUserNotificationSettings
volverá: UIUserNotificationTypeNone
en ese caso. Esto no es realmente indicativo de la configuración real de los usuarios.
Algunas conjeturas que uno puede hacer:
- si
isRegisteredForRemoteNotifications
esNO
entonces puede asumir que este dispositivo nunca se ha registrado correctamente para las notificaciones remotas. - después de la primera vez que se registra para recibir notificaciones remotas, se realiza una devolución de llamada a
application:didRegisterUserNotificationSettings:
que contiene la configuración de notificaciones del usuario en este momento, ya que esta es la primera vez que un el usuario ha sido registrado la configuración debe indicar lo que el usuario seleccionó en términos de la solicitud de permiso. Si la configuración equivale a cualquier otra cosa que no sea:UIUserNotificationTypeNone
, entonces se concedió el permiso push, de lo contrario se rechazó. La razón de esto es que desde el momento en que comienza el proceso de registro remoto, el usuario solo tiene la capacidad de aceptar o rechazar, con la configuración inicial de una aceptación siendo la configuración que configuró durante el proceso de registro.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-25 14:36:11
Para completar la respuesta, podría funcionar algo como esto...
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
switch (types) {
case UIRemoteNotificationTypeAlert:
case UIRemoteNotificationTypeBadge:
// For enabled code
break;
case UIRemoteNotificationTypeSound:
case UIRemoteNotificationTypeNone:
default:
// For disabled code
break;
}
Editar: Esto no está bien. dado que estas son cosas en cuanto a bits, no funcionará con un interruptor, así que terminé usando esto:
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
UIRemoteNotificationType typesset = (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
if((types & typesset) == typesset)
{
CeldaSwitch.chkSwitch.on = true;
}
else
{
CeldaSwitch.chkSwitch.on = false;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-08 18:33:37
Para iOS7 y antes debe usar enabledRemoteNotificationTypes
y verificar si es igual (o no es igual dependiendo de lo que desee) a UIRemoteNotificationTypeNone
.
Sin embargo para iOS8 es no siempre suficiente para comprobar solo con isRegisteredForRemoteNotifications
como muchos de los estados anteriores. También debes comprobar si application.currentUserNotificationSettings.types
es igual (o no es igual dependiendo de lo que quieras) UIUserNotificationTypeNone
!
isRegisteredForRemoteNotifications
puede devolver true aunque currentUserNotificationSettings.types
devuelva UIUserNotificationTypeNone
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-04 14:23:27
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types & UIRemoteNotificationTypeAlert)
// blah blah blah
{
NSLog(@"Notification Enabled");
}
else
{
NSLog(@"Notification not enabled");
}
Aquí obtenemos el UIRemoteNotificationType de UIApplication. Representa el estado de notificación push de esta aplicación en la configuración, que se puede comprobar en su tipo fácilmente
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-18 13:59:57
Trato de soportar iOS 10 y superiores utilizando la solución proporcionada por @Shaheen Ghiassy, pero encuentro un problema de privación enabledRemoteNotificationTypes
. Por lo tanto, la solución que encuentro usando isRegisteredForRemoteNotifications
en lugar de enabledRemoteNotificationTypes
que estaba en desuso en iOS 8. A continuación se muestra mi solución actualizada que funcionó perfectamente para mí:
- (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 {
if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
isEnabled = YES;
} else{
isEnabled = NO;
}
}
return isEnabled;
}
Y podemos llamar a esta función fácilmente y acceder a su valor Bool
y podemos convertirlo en el valor de cadena de esta manera:
NSString *str = [self notificationServicesEnabled] ? @"YES" : @"NO";
Espero que ayude a otros también :) Feliz codificación.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-10 11:30:03
IOS8 + (OBJETIVO C)
#import <UserNotifications/UserNotifications.h>
[[UNUserNotificationCenter currentNotificationCenter]getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
switch (settings.authorizationStatus) {
case UNAuthorizationStatusNotDetermined:{
break;
}
case UNAuthorizationStatusDenied:{
break;
}
case UNAuthorizationStatusAuthorized:{
break;
}
default:
break;
}
}];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-06 10:54:36
Aunque la respuesta de Zac era perfectamente correcta hasta iOS 7, ha cambiado desde que llegó iOS 8. Porque enabledRemoteNotificationTypes ha quedado obsoleto a partir de iOS 8. Para iOS 8 y versiones posteriores, debe usar Isregistered Forremotenotifications.
- para iOS 7 y antes Use > Use enabledRemoteNotificationTypes
- para iOS 8 y versiones posteriores > > El uso está registrado para Remotenotificaciones.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-15 15:01:26
Esta solución Swifty funcionó bien para mí ( iOS8+),
Método:
func isNotificationEnabled(completion:@escaping (_ enabled:Bool)->()){
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
let status = (settings.authorizationStatus == .authorized)
completion(status)
})
} else {
if let status = UIApplication.shared.currentUserNotificationSettings?.types{
let status = status.rawValue != UIUserNotificationType(rawValue: 0).rawValue
completion(status)
}else{
completion(false)
}
}
}
Uso :
isNotificationEnabled { (isEnabled) in
if isEnabled{
print("Push notification enabled")
}else{
print("Push notification not enabled")
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-21 10:00:16
Re:
Esto es correcto
if (types & UIRemoteNotificationTypeAlert)
¡Pero seguir también es correcto ! (como UIRemoteNotificationTypeNone es 0 )
if (types == UIRemoteNotificationTypeNone)
Véase lo siguiente
NSLog(@"log:%d",0 & 0); ///false
NSLog(@"log:%d",1 & 1); ///true
NSLog(@"log:%d",1<<1 & 1<<1); ///true
NSLog(@"log:%d",1<<2 & 1<<2); ///true
NSLog(@"log:%d",(0 & 0) && YES); ///false
NSLog(@"log:%d",(1 & 1) && YES); ///true
NSLog(@"log:%d",(1<<1 & 1<<1) && YES); ///true
NSLog(@"log:%d",(1<<2 & 1<<2) && YES); ///true
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-16 02:48:57
Aquí está cómo hacer esto en Xamarin.ios.
public class NotificationUtils
{
public static bool AreNotificationsEnabled ()
{
var settings = UIApplication.SharedApplication.CurrentUserNotificationSettings;
var types = settings.Types;
return types != UIUserNotificationType.None;
}
}
Si está soportando iOS 10+ solo vaya con el método UNUserNotificationCenter.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-01 11:18:26
En Xamarin, toda la solución anterior no funciona para mí. Esto es lo que uso en su lugar:
public static bool IsRemoteNotificationsEnabled() {
return UIApplication.SharedApplication.CurrentUserNotificationSettings.Types != UIUserNotificationType.None;
}
También recibe una actualización en vivo después de haber cambiado el estado de la notificación en Configuración.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-21 03:58:44
Copie y pegue fácilmente el código creado a partir de la solución de @ZacBowling ( https://stackoverflow.com/a/1535427/2298002 )
Esto también llevará al usuario a la configuración de su aplicación y le permitirá habilitar inmediatamente
También agregué una solución para verificar si los servicios de ubicación están habilitados (y también trae a la configuración)
// check if notification service is enabled
+ (void)checkNotificationServicesEnabled
{
if (![[UIApplication sharedApplication] isRegisteredForRemoteNotifications])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notification Services Disabled!"
message:@"Yo don't mess around bro! Enabling your Notifications allows you to receive important updates"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Settings", nil];
alertView.tag = 300;
[alertView show];
return;
}
}
// check if location service is enabled (ref: https://stackoverflow.com/a/35982887/2298002)
+ (void)checkLocationServicesEnabled
{
//Checking authorization status
if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled!"
message:@"You need to enable your GPS location right now!!"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Settings", nil];
//TODO if user has not given permission to device
if (![CLLocationManager locationServicesEnabled])
{
alertView.tag = 100;
}
//TODO if user has not given permission to particular app
else
{
alertView.tag = 200;
}
[alertView show];
return;
}
}
// handle bringing user to settings for each
+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)// Cancel button pressed
{
//TODO for cancel
}
else if(buttonIndex == 1)// Settings button pressed.
{
if (alertView.tag == 100)
{
//This will open ios devices location settings
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
}
else if (alertView.tag == 200)
{
//This will open particular app location settings
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
else if (alertView.tag == 300)
{
//This will open particular app location settings
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
}
}
GLHF!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:24