Recibir mensajes en una aplicación de Apple

Una vez que su aplicación cliente está instalada en un dispositivo, puede recibir mensajes a través de la interfaz de FCM APN. Puede comenzar a enviar notificaciones inmediatamente a segmentos de usuarios con el redactor de notificaciones o mensajes creados en su servidor de aplicaciones.

Manejar notificaciones de alerta

FCM entrega todos los mensajes dirigidos a aplicaciones de Apple a través de APN. Para obtener más información sobre cómo recibir notificaciones de APN a través de UNUserNotificationCenter, consulte la documentación de Apple sobre Manejo de notificaciones y acciones relacionadas con notificaciones .

Debe configurar el delegado de UNUserNotificationCenter e implementar los métodos de delegado adecuados para recibir notificaciones de visualización de FCM.

Rápido


extension AppDelegate: UNUserNotificationCenterDelegate {
  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification) async
    -> UNNotificationPresentationOptions {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // ...

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    return [[.alert, .sound]]
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse) async {
    let userInfo = response.notification.request.content.userInfo

    // ...

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print full message.
    print(userInfo)
  }
}

C objetivo

// Receive displayed notifications for iOS 10 devices.
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  NSDictionary *userInfo = notification.request.content.userInfo;

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // ...

  // Print full message.
  NSLog(@"%@", userInfo);

  // Change this to your preferred presentation option
  completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}

// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void(^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler();
}

Si desea agregar acciones personalizadas a sus notificaciones, configure el parámetro click_action en la carga útil de la notificación . Utilice el valor que usaría para la clave category en la carga útil de APN. Las acciones personalizadas deben registrarse antes de poder utilizarlas. Para obtener más información, consulte la Guía de programación de notificaciones locales y remotas de Apple.

Para obtener información sobre la entrega de mensajes a su aplicación, consulte el panel de informes de FCM , que registra la cantidad de mensajes enviados y abiertos en dispositivos Apple y Android, junto con datos de "impresiones" (notificaciones vistas por los usuarios) para aplicaciones de Android.

Manejar notificaciones push silenciosas

Al enviar mensajes con la clave content_available (equivalente a content-available de APN, los mensajes se entregarán como notificaciones silenciosas, activando su aplicación en segundo plano para tareas como la actualización de datos en segundo plano. A diferencia de las notificaciones en primer plano, estas notificaciones deben manejarse a través de la application(_:didReceiveRemoteNotification:fetchCompletionHandler:) método.

Implemente application(_:didReceiveRemoteNotification:fetchCompletionHandler:) como se muestra:

Rápido

func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async
  -> UIBackgroundFetchResult {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  return UIBackgroundFetchResult.newData
}

C objetivo

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // ...

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler(UIBackgroundFetchResultNewData);
}

Las plataformas de Apple no garantizan la entrega de notificaciones en segundo plano. Para conocer las condiciones que pueden provocar que fallen las notificaciones en segundo plano, consulte los documentos de Apple sobre cómo enviar actualizaciones en segundo plano a su aplicación .

Interpretación de la carga útil del mensaje de notificación

La carga útil de los mensajes de notificación es un diccionario de claves y valores. Los mensajes de notificación enviados a través de APN siguen el formato de carga útil de APN como se muestra a continuación:

  {
    "aps" : {
      "alert" : {
        "body" : "great match!",
        "title" : "Portugal vs. Denmark",
      },
      "badge" : 1,
    },
    "customKey" : "customValue"
  }

Manejar mensajes con el método swizzling deshabilitado

De forma predeterminada, si asigna la clase de delegado de aplicación de su aplicación a las propiedades de delegado UNUserNotificationCenter y Messaging , FCM cambiará la clase de delegado de su aplicación para asociar automáticamente su token de FCM con el token de APN del dispositivo y pasar los eventos de notificación recibida a Analytics. Si deshabilita explícitamente el método swizzling, si está creando una aplicación SwiftUI o si usa una clase separada para cada delegado, deberá realizar ambas tareas manualmente.

Para asociar el token de FCM con el token de APN del dispositivo, pase el token de APN a la clase Messaging en el controlador de actualización de token del delegado de su aplicación a través de la propiedad apnsToken .

Rápido

func application(_ application: UIApplication,
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  Messaging.messaging().apnsToken = deviceToken;
}
 

C objetivo

- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [FIRMessaging messaging].APNSToken = deviceToken;
}

Para pasar información de recepción de notificación a Analytics, utilice el método appDidReceiveMessage(_:) .

Rápido

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
  withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  let userInfo = notification.request.content.userInfo

  Messaging.messaging().appDidReceiveMessage(userInfo)

  // Change this to your preferred presentation option
  completionHandler([[.alert, .sound]])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
  let userInfo = response.notification.request.content.userInfo

  Messaging.messaging().appDidReceiveMessage(userInfo)

  completionHandler()
}

func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
   fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  Messaging.messaging().appDidReceiveMessage(userInfo)
  completionHandler(.noData)
}

C objetivo

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  NSDictionary *userInfo = notification.request.content.userInfo;

  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Change this to your preferred presentation option
  completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void(^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;

  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  completionHandler();
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
  completionHandler(UIBackgroundFetchResultNoData);
}