ver recuperar pantalla notificaciones historial funciona como centro borradas bloqueada ios uikit apple-push-notifications uilocalnotification toast

ios - pantalla - recuperar notificaciones iphone



¿Muestra un banner de notificación de iOS en stock cuando su aplicación está abierta y en primer plano? (10)

Cuando la aplicación oficial de mensajes de iOS de Apple está abierta y en primer plano, los nuevos mensajes de otros contactos activan un banner de alerta de notificación de iOS nativo. Ver imagen a continuación.

¿Es esto posible en aplicaciones de terceros en App Store? ¿Notificaciones locales y / o push para su aplicación mientras su aplicación está abierta y en primer plano ?

Al probar mi aplicación , se reciben notificaciones pero no se muestra la IU de alerta de iOS .

Pero este comportamiento se ve en la aplicación oficial de Mensajes de Apple:

La Guía de programación de notificaciones locales y remotas dice:

Cuando el sistema operativo entrega una notificación local o remota y la aplicación de destino no se está ejecutando en primer plano , puede presentar la notificación al usuario a través de una alerta , un número de insignia de icono o un sonido.

Si la aplicación se ejecuta en primer plano cuando se entrega la notificación, el delegado de la aplicación recibe una notificación local o remota.

Entonces sí, podemos recibir los datos de notificación mientras estamos en primer plano. Pero no veo forma de presentar la IU de alerta de notificación nativa de iOS .

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { // I know we still receive the notification `userInfo` payload in the foreground. // This question is about displaying the stock iOS notification alert UI. // Yes, one *could* use a 3rd party toast alert framework. [self use3rdPartyToastAlertFrameworkFromGithub] }

¿Utiliza Messages una API privada para mostrar la alerta mientras está en primer plano?

A los fines de esta pregunta, no sugiera ninguna alerta emergente de "brindis" de terceros en github o etc. Solo me interesa si esto se puede hacer utilizando la interfaz de usuario original, local de iOS o alertas de notificaciones push mientras su La aplicación está abierta y en primer plano .


Aquí está el código para recibir notificaciones push cuando la aplicación está en primer plano o en etapa abierta, iOS 10 y Swift 2.3

@available(iOS 10.0, *) func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { completionHandler([UNNotificationPresentationOptions.Alert,UNNotificationPresentationOptions.Sound,UNNotificationPresentationOptions.Badge]) }

Si necesita acceder a la información de usuario de la notificación, use el código: notify.request.content.userInfo

El método userNotificationCenter(_:willPresent:withCompletionHandler:) solo se llama si agrega a la carga útil el atributo content-available:1 . La carga útil final debería ser algo como:

{ "aps":{ "alert":"Testing.. (7)", "badge":1,"sound":"default" }, "content-available":1 }


Para mostrar notificaciones locales, esta es la mejor opción. necesita menos código para escribir "BRYXBanner" https://cocoapods.org/pods/BRYXBanner

let banner = Banner(title: "title", subtitle: "subtitle", image: UIImage(named: "addContact"), backgroundColor: UIColor(red:137.0/255.0, green:172.0/255.0, blue:2.0/255.0, alpha:1.000)) banner.dismissesOnTap = true banner.show(duration: 1.0)


Para mostrar notificaciones mientras la aplicación está abierta, debemos manejarla manualmente. Entonces, lo que estoy haciendo a continuación es manejar la notificación una vez recibida.

Agregue todo a continuación en AppDelegate.m

  1. Manejar llamada para notificar
  2. Cree una vista, agregue AppIcon, mensaje de notificación y muéstrelo como una animación
  3. Agregue el reconocedor táctil para eliminar si se toca o elimine en 5 segundos con animación.

Avíseme si esta es una solución correcta. Funcionó bien para mí, pero no estoy seguro si esta es la forma correcta.

- (void)application:(UIApplication *)applicationdidReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { NSString *notifMessage = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]; //Define notifView as UIView in the header file [_notifView removeFromSuperview]; //If already existing _notifView = [[UIView alloc] initWithFrame:CGRectMake(0, -70, self.window.frame.size.width, 80)]; [_notifView setBackgroundColor:[UIColor blackColor]]; UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10,15,30,30)]; imageView.image = [UIImage imageNamed:@"AppLogo.png"]; UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 15, self.window.frame.size.width - 100 , 30)]; myLabel.font = [UIFont fontWithName:@"Helvetica" size:10.0]; myLabel.text = notifMessage; [myLabel setTextColor:[UIColor whiteColor]]; [myLabel setNumberOfLines:0]; [_notifView setAlpha:0.95]; //The Icon [_notifView addSubview:imageView]; //The Text [_notifView addSubview:myLabel]; //The View [self.window addSubview:_notifView]; UITapGestureRecognizer *tapToDismissNotif = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissNotifFromScreen)]; tapToDismissNotif.numberOfTapsRequired = 1; tapToDismissNotif.numberOfTouchesRequired = 1; [_notifView addGestureRecognizer:tapToDismissNotif]; [UIView animateWithDuration:1.0 delay:.1 usingSpringWithDamping:0.5 initialSpringVelocity:0.1 options:UIViewAnimationOptionCurveEaseIn animations:^{ [_notifView setFrame:CGRectMake(0, 0, self.window.frame.size.width, 60)]; } completion:^(BOOL finished) { }]; //Remove from top view after 5 seconds [self performSelector:@selector(dismissNotifFromScreen) withObject:nil afterDelay:5.0]; return; } //If the user touches the view or to remove from view after 5 seconds - (void)dismissNotifFromScreen{ [UIView animateWithDuration:1.0 delay:.1 usingSpringWithDamping:0.5 initialSpringVelocity:0.1 options:UIViewAnimationOptionCurveEaseIn animations:^{ [_notifView setFrame:CGRectMake(0, -70, self.window.frame.size.width, 60)]; } completion:^(BOOL finished) { }]; }


Para mostrar un mensaje de banner mientras la aplicación está en primer plano, use el siguiente método.

iOS 10, Swift 3 :

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .badge, .sound]) }


Puede manejar la notificación usted mismo y mostrar una alerta personalizada. Aplicaciones como Viber, Whatsapp y BisPhone utilizan este enfoque.

Un ejemplo de alerta personalizada de terceros es CRToast .

Intente programar una notificación local mientras su aplicación está en primer plano, y verá que no se muestra ninguna alerta de iOS:

if (application.applicationState == UIApplicationStateActive ) { UILocalNotification *localNotification = [[UILocalNotification alloc] init]; localNotification.userInfo = userInfo; localNotification.soundName = UILocalNotificationDefaultSoundName; localNotification.alertBody = message; localNotification.fireDate = [NSDate date]; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; }


Si su objetivo de implementación> = iOS10, use UNUserNotification como a continuación:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // Change this to your preferred presentation option completionHandler([.alert, .sound]) }


EDITAR:

¡Las alertas en primer plano ahora son posibles en iOS 10! Por favor vea esta respuesta .

Para iOS 9 y a continuación:

No parece posible mostrar la alerta de notificación de stock de iOS cuando su aplicación está abierta y en primer plano. Messages.app debe estar utilizando una API privada.

El sistema no muestra ninguna alerta, muestra el icono de la aplicación ni reproduce ningún sonido cuando la aplicación ya está en primer plano. - Documentos de notificación UILocal

Se UIApplicationDelegate métodos UIApplicationDelegate , lo que permitirá que su aplicación responda a la notificación local o remota:

application:didReceiveLocalNotification: application:didReceiveRemoteNotification:

Sin embargo, la IU del banner de alerta de notificación nativa de iOS no se mostrará como está en los mensajes de Apple, que deben estar utilizando una API privada.

Lo mejor que puede hacer es desplegar su propio banner de alerta o usar un marco existente:

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { // Use a 3rd party toast alert framework to display a banner [self toastAlertFromGithub] }

He abierto un radar para este comportamiento aquí: rdar://22313177


Versión Swift 3

Esto muestra una alerta cuando la aplicación está en primer plano.

if #available(iOS 10.0, *) { // need to setup the global notification delegate somewhere when your app starts // UNUserNotificationCenter.current().delegate = applicationDelegate // to show a message // let content = UNMutableNotificationContent() content.body = "MESSAGE" let request = UNNotificationRequest(identifier: "fred", content: content, trigger: nil) UNUserNotificationCenter.current().add(request) { error in // called when message has been sent debugPrint("Error: /(error)") } }

Implementación de UNUserNotificationCenterDelegate de UNUserNotificationCenterDelegate

@available(iOS 10.0, *) public func userNotificationCenter(_ center : UNUserNotificationCenter, willPresent notification : UNNotification, withCompletionHandler completionHandler : @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert]) // only-always show the alert }


iOS 10 agrega el protocolo UNUserNotificationCenterDelegate para manejar las notificaciones mientras su aplicación está en primer plano.

El protocolo UNUserNotificationCenterDelegate define métodos para recibir notificaciones y para manejar acciones. Cuando su aplicación está en primer plano, las notificaciones que llegan se entregan a su objeto delegado en lugar de mostrarse automáticamente mediante las interfaces del sistema.

Rápido:

optional func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)

C objetivo:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler;

Los indicadores UNNotificationPresentationOptions permiten especificar UNNotificationPresentationOptionAlert para mostrar una alerta utilizando el texto proporcionado por la notificación.

Esta es la clave, ya que le permite mostrar la alerta mientras su aplicación está abierta y en primer plano , lo cual es nuevo para iOS 10.

Código de muestra:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) }


UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.body = body; content.userInfo = userInfo; content.sound = [UNNotificationSound defaultSound]; [content setValue:@(YES) forKeyPath:@"shouldAlwaysAlertWhileAppIsForeground"]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"Notif" content:content trigger:nil]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { DLog(@"Error:%@", error); }];

Puedo mostrar notificaciones push cuando la aplicación está activa para iOS 10.

  1. La notificación push del servidor debe ser silenciosa .

  2. Cuando recibe una notificación remota del servidor, envía una notificación local y establece el valor de keyPath: shouldAlwaysAlertWhileAppIsForeground = True