Recibe mensajes en una app para Apple

Una vez instalada en el dispositivo, la app cliente puede recibir mensajes mediante la interfaz de APNS que ofrece FCM. Puedes comenzar a enviar notificaciones de inmediato a segmentos de usuarios con el Compositor de Notifications o con mensajes creados en tu servidor de aplicaciones.

Administra las notificaciones de alerta

FCM entrega todos los mensajes segmentados a apps para Apple mediante APNS. Si necesitas más información para recibir notificaciones de APNS mediante UNUserNotificationCenter, consulta la documentación de Apple sobre cómo administrar las notificaciones y las acciones relacionadas con ellas.

Debes configurar el delegado de UNUserNotificationCenter y, luego, implementar los métodos de delegado adecuados para recibir notificaciones en pantalla de FCM.

Swift


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

Objective‑C

// 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 quieres agregar acciones personalizadas a las notificaciones, configura el parámetro click_action en la carga útil de la notificación. Usa el valor que emplearías con normalidad para la clave category en la carga útil de APNS. Debes registrar las acciones personalizadas para poder usarlas. Si necesitas más información, consulta la guía de programación para notificaciones locales y remotas de Apple.

Para obtener información sobre la entrega de mensajes en tu app, consulta el panel de informes de FCM, en el que se registra la cantidad de mensajes que se enviaron y abrieron en dispositivos Apple y Android, junto con datos de “impresiones” (las notificaciones que ven los usuarios) de las apps para Android.

Administra notificaciones push silenciosas

Cuando envíes mensajes con la clave content_available (equivalente a la clave content-available de APN), estos se enviarán como notificaciones silenciosas, y tu app se activará en segundo plano para realizar tareas como actualizar datos en segundo plano. A diferencia de las notificaciones en primer plano, estas notificaciones deben administrarse mediante el método application(_:didReceiveRemoteNotification:fetchCompletionHandler:).

Implementa application(_:didReceiveRemoteNotification:fetchCompletionHandler:) de la siguiente manera:

Swift

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
}

Objective‑C

- (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. Si necesitas información sobre las condiciones que pueden causar fallas en las notificaciones en segundo plano, consulta los documentos de Apple acerca del envío de actualizaciones en segundo plano a la app.

Interpreta 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 APNS usan el formato de carga útil de APNS que se muestra a continuación:

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

Administra mensajes con el swizzling de métodos inhabilitado

De forma predeterminada, si asignas la clase delegada de la app a las propiedades delegadas UNUserNotificationCenter y Messaging, FCM aplicará swizzling a la clase delegada para asociar automáticamente el token de FCM con el token de APNS del dispositivo y pasar los eventos recibidos por notificaciones a Analytics. Si inhabilitas el swizzling de métodos de manera explícita, si compilas una app de SwiftUI o si usas una clase independiente para cualquiera de los delegados, deberás realizar ambas tareas de forma manual.

Para asociar el token de FCM con el token de APNS del dispositivo, pasa el token de APNS a la clase Messaging en el controlador de actualización de tokens del delegado de tu app mediante la propiedad apnsToken.

Swift

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

Objective‑C

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

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

Swift

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

Objective-C

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