notificaciones mail funciona correo centro activar ios iphone notifications apple-push-notifications push

ios - mail - Determine en el iPhone si el usuario ha habilitado las notificaciones push



notificaciones push iphone instagram (19)

Estoy buscando una manera de determinar si el usuario tiene, a través de la configuración, habilitado o deshabilitado sus notificaciones push para mi aplicación.


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; } }];


A continuación encontrará un ejemplo completo que cubre tanto iOS8 como iOS7 (y versiones inferiores). Tenga en cuenta que antes de iOS8 no puede distinguir entre "notificaciones remotas deshabilitadas" y "solo ver en pantalla de bloqueo habilitada".

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");


Al intentar admitir tanto iOS8 como inferior, no tuve mucha suerte al usar isRegisteredForRemoteNotifications como sugirió Kevin. En su lugar, utilicé 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; }


Aquí es 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.


Aunque la respuesta de Zac fue perfectamente correcta hasta iOS 7, ha cambiado desde que llegó iOS 8. Porque enabledRemoteNotificationTypes ha quedado en desuso desde iOS 8 en adelante. Para iOS 8 y versiones posteriores, debe usar isRegisteredForRemoteNotifications .

  • para iOS 7 y anteriores -> Usar enabledRemoteNotificationTypes
  • para iOS 8 y versiones posteriores -> Use isRegisteredForRemoteNotifications.

Código completo fácil de copiar y pegar creado a partir de la solución de @ ZacBowling ( https://.com/a/1535427/2298002 )

Esto también llevará al usuario a la configuración de su aplicación y le permitirá habilitarlo inmediatamente.

También agregué una solución para verificar si los servicios de ubicación están habilitados (y también 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://.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!


Desafortunadamente, ninguna de estas soluciones proporcionadas realmente resuelve el problema porque al final del día faltan las API cuando se trata de proporcionar la información pertinente. Puede hacer algunas conjeturas, sin embargo, el uso de currentUserNotificationSettings (iOS8 +) no es suficiente en su forma actual para responder realmente la pregunta. Aunque muchas de las soluciones aquí parecen sugerir que eso o isRegisteredForRemoteNotifications es más una respuesta definitiva, realmente no lo es.

Considera esto:

isRegisteredForRemoteNotifications estados de la documentación de isRegisteredForRemoteNotifications :

Devuelve SÍ si la aplicación está actualmente registrada para notificaciones remotas, teniendo en cuenta cualquier configuración del sistema ...

Sin embargo, si lanza un NSLog simple en el delegado de su aplicación para observar el comportamiento, está claro que esto no se comporta de la forma 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 por primera vez, siempre volverá YES . Incluso si los desactiva en la configuración (notificaciones) seguirá dando como resultado que sí, esto se debe a que, a partir de iOS8, una aplicación puede registrarse para recibir notificaciones remotas e incluso enviarlas a un dispositivo sin que el usuario tenga las notificaciones habilitadas, es posible que no puedan hacer alertas. , Insignias y Sonido sin que el usuario lo encienda. Las notificaciones silenciosas son un buen ejemplo de algo que puede seguir haciendo incluso con las notificaciones desactivadas.

En cuanto a currentUserNotificationSettings , indica una de cuatro cosas:

Las alertas están activadas Las insignias están activadas El sonido está activado Ninguna está activada.

Esto no le da absolutamente ninguna indicación sobre los otros factores o el propio interruptor de Notificación.

De hecho, un usuario puede desactivar las insignias, el sonido y las alertas, pero aún así puede mostrar en la pantalla de bloqueo o en el centro de notificaciones. Este usuario aún debe recibir notificaciones automáticas y poder verlas tanto en la pantalla de bloqueo como en el centro de notificaciones. Tienen el interruptor de notificación encendido. PERO currentUserNotificationSettings devolverá: 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 es NO , puede asumir que este dispositivo nunca se ha registrado correctamente para recibir notificaciones remotas.
  • después de la primera vez que se registre para notificaciones remotas, se realiza una devolución de llamada a la application:didRegisterUserNotificationSettings: contiene la configuración de notificación del usuario en este momento, ya que esta es la primera vez que se registra un usuario. La configuración debe indicar lo que el usuario seleccionó en términos de la solicitud de permiso. . Si la configuración equivale a algo diferente a: UIUserNotificationTypeNone , se otorgó 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, siendo la configuración inicial de una aceptación la configuración que usted configuró durante el proceso de registro.

En Xamarin, todas las soluciones anteriores no funcionan para mí. Esto es lo que uso en su lugar:

public static bool IsRemoteNotificationsEnabled() { return UIApplication.SharedApplication.CurrentUserNotificationSettings.Types != UIUserNotificationType.None; }

Está recibiendo una actualización en vivo también después de haber cambiado el estado de notificación en Configuración.


En la última versión de iOS, este método ahora está en desuso. Para admitir el uso de iOS 7 y iOS 8:

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; }


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") } }

Ref


Intento con el soporte de iOS 10 y superior utilizando la solución provista por @Shaheen Ghiassy pero encuentro el problema de la privación enabledRemoteNotificationTypes , enabledRemoteNotificationTypes . Por lo tanto, la solución que encuentro al usar isRegisteredForRemoteNotifications lugar de enabledRemoteNotificationTypes obsoleta en iOS 8. A continuación, se encuentra 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 convertirlo en el valor de la cadena de esta manera:

NSString *str = [self notificationServicesEnabled] ? @"YES" : @"NO";

Espero que ayude a otros también :) Feliz codificación.


No puedo comentar (no tengo suficiente reputación), pero re: quantumpotato''s problem:

Donde los types son dados por

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];

uno 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, distintivos, centro de notificaciones, etc.). La primera línea de código ( types & UIRemoteNotificationTypeAlert ) devolverá YES si el "Estilo de alerta" está configurado como "Banners" o "Alertas", y NO si el "Estilo de alerta" está configurado como "Ninguno", independientemente de otras configuraciones.


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; }

Edición: Esto no está bien. ya que estas son cosas poco inteligentes, 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; }


Para iOS7 y antes, debe utilizar enabledRemoteNotificationTypes y verificar si es igual (o no es igual en función de lo que quiera) a UIRemoteNotificationTypeNone .

Sin embargo, para iOS8 no siempre es suficiente verificar solo con isRegisteredForRemoteNotifications como muchos estados anteriores. También debe verificar si application.currentUserNotificationSettings.types es igual (o no es igual en función de lo que quiera) UIUserNotificationTypeNone !

isRegisteredForRemoteNotifications puede devolver verdadero incluso aunque currentUserNotificationSettings.types devuelve UIUserNotificationTypeNone .


re:

esto es correcto

if (types & UIRemoteNotificationTypeAlert)

¡Pero lo siguiente es correcto también! (como UIRemoteNotificationTypeNone es 0)

if (types == UIRemoteNotificationTypeNone)

ver 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


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á en desuso, 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 verifica 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 }


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 }

Versión observable RxSwift 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() } } }


Llame a enabledRemoteNotificationsTypes y verifique la máscara.

Por ejemplo:

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes]; if (types == UIRemoteNotificationTypeNone) // blah blah blah

iOS8 y superior:

[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]


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 de inserción de esta aplicación en la configuración, que puede verificar fácilmente en su tipo