Recevoir des messages dans une application Apple

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

Gérer les notifications d'alerte

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

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 d'affichage de FCM.

Rapide


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

Objectif 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 APN. Les actions personnalisées doivent être enregistrées avant de pouvoir être utilisées. Pour plus d'informations, consultez le Guide de programmation des notifications locales et distantes d'Apple.

Pour obtenir un aperçu de la transmission 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

Lors de l'envoi de messages avec la clé content_available (équivalente à content-available des APN, les messages seront envoyés sous forme de notifications silencieuses, réveillant 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 via l' application(_:didReceiveRemoteNotification:fetchCompletionHandler:) Méthode application(_:didReceiveRemoteNotification:fetchCompletionHandler:) .

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

Rapide

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
}

Objectif 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 plateformes Apple ne garantissent pas l'envoi de notifications en arrière-plan. Pour en savoir plus sur les conditions pouvant entraîner l'échec des notifications en arrière-plan, consultez la documentation d'Apple sur l'envoi de mises à jour en arrière-plan vers votre application .

Interprétation de la charge utile du message 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 les APN suivent le format de charge utile des APN comme ci-dessous :

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

Gérer les messages avec la méthode swizzling désactivée

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 fera pivoter votre classe de délégué d'application pour associer automatiquement votre jeton FCM au jeton APNs de l'appareil et transmettre les événements de notification reçus à 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 de jeton de votre délégué d'application via la propriété apnsToken .

Rapide

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

Objectif c

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

Pour transmettre les informations de réception de notification à Analytics, utilisez la méthode appDidReceiveMessage(_:) .

Rapide

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

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