Recevoir des messages dans une application Apple

Une fois votre application cliente installée sur un appareil, elle peut recevoir des messages via l'interface APNs FCM. Vous pouvez immédiatement commencer à envoyer des notifications à des segments d'utilisateurs avec le compositeur de notifications ou des messages créés sur votre serveur d'application.

Gérer les notifications d'alerte

FCM transmet tous les messages ciblant les applications Apple via APNs. Pour en savoir plus sur la réception des notifications APNs via UNUserNotificationCenter, consultez la documentation Apple sur la gestion des notifications et des actions associées.

Vous devez définir le délégué UNUserNotificationCenter et implémenter les méthodes de délégué appropriées pour recevoir les notifications à afficher depuis 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 vous souhaitez ajouter des actions personnalisées à vos notifications, définissez le paramètre click_action dans la charge utile de notification. Utilisez la valeur que vous utiliseriez pour la clé category dans la charge utile APNs. Les actions personnalisées doivent être enregistrées avant de pouvoir être utilisées. Pour en savoir plus, consultez le guide de programmation des notifications locales et à distance d'Apple.

Pour obtenir des informations sur la distribution des messages à votre application, consultez le tableau de bord de reporting FCM, qui enregistre le nombre de messages envoyés et ouverts sur les appareils Apple et Android, ainsi que les données sur les "impressions" (notifications vues par les utilisateurs) pour les applications Android.

Gérer les notifications push silencieuses

Lorsque vous envoyez des messages avec la clé content-available (équivalente à content-available d'APNs), ils sont distribués sous forme de notifications silencieuses, ce qui réveille votre application en arrière-plan pour des tâches telles que l'actualisation des données en arrière-plan. Contrairement aux notifications au premier plan, ces notifications doivent être gérées à l'aide de la méthode application(_:didReceiveRemoteNotification:fetchCompletionHandler:).

Implémentez application(_:didReceiveRemoteNotification:fetchCompletionHandler:) comme indiqué ci-dessous :

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

Les plates-formes Apple ne garantissent pas la distribution des notifications en arrière-plan. Pour en savoir plus sur les conditions qui peuvent entraîner l'échec des notifications en arrière-plan, consultez la documentation Apple sur l'envoi de mises à jour en arrière-plan à votre application.

Interpréter la charge utile des messages de notification

La charge utile des messages de notification est un dictionnaire de clés et de valeurs. Les messages de notification envoyés via APNs suivent le format de charge utile APNs ci-dessous :

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

Gérer les messages lorsque le swizzling de méthode est désactivé

Par défaut, si vous attribuez la classe de délégué d'application de votre application aux propriétés de délégué UNUserNotificationCenter et Messaging, FCM permutera la classe de délégué d'application pour associer automatiquement votre jeton FCM au jeton APNs de l'appareil et transmettra les événements de notification reçue à Analytics. Si vous désactivez explicitement le swizzling de méthode, si vous créez une application SwiftUI ou si vous utilisez une classe distincte pour l'un ou l'autre des délégués, vous devrez effectuer ces deux tâches manuellement.

Pour associer le jeton FCM au jeton APNs de l'appareil, transmettez le jeton APNs à la classe Messaging dans le gestionnaire d'actualisation du jeton du délégué de votre application via la propriété 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;
}

Pour transmettre les informations de réception des notifications à Analytics, utilisez la méthode 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);
}