Une fois votre application cliente installée sur un appareil, elle peut recevoir des messages via l'interface APNs FCM. Vous pouvez commencer immédiatement l'envoi de notifications aux segments d'utilisateurs l'outil de composition des notifications ou les messages créés à partir de votre serveur d'applications.
Gérer les notifications d'alerte
FCM diffuse tous les messages ciblant les applications Apple via un 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 associées aux notifications.
Vous devez définir le paramètre Délégué UNUserNotificationCenter et implémenter les méthodes de délégation appropriées pour recevoir les notifications d'affichage. 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 vous souhaitez ajouter des actions personnalisées à vos notifications, définissez le
paramètre click_action
dans
charge utile de notification.
Utilisez la valeur que vous utiliseriez pour le paramètre
Clé category
dans la charge utile APNs. Les actions personnalisées doivent être enregistrées au préalable
ils peuvent être utilisés. Pour en savoir plus, consultez le site
Guide de programmation des notifications locales et à distance
Pour en savoir plus sur la distribution de messages dans votre application, consultez le <ph type="x-smartling-placeholder"></ph> FCM, tableau de bord de reporting, qui enregistre le nombre de messages envoyés et ouverts sur des appareils Apple et Android, ainsi que de données sur les "impressions" (notifications visibles 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
des APN), les messages sont distribués en tant que notifications silencieuses, ce qui réveille votre application en arrière-plan pour des tâches telles que la mise à jour des données en arrière-plan.
Contrairement aux notifications de premier plan, ces notifications doivent être gérées via la méthode application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
.
Implémenter 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 pouvant entraîner l'échec des notifications en arrière-plan, consultez la documentation d'Apple sur l'envoi d'informations en arrière-plan à votre application.
Interpréter la charge utile du message de notification
La charge utile des messages de notification est un dictionnaire clés et valeurs. Les messages de notification envoyés via APNs suivent le flux APNs format de données utiles comme ci-dessous:
{ "aps" : { "alert" : { "body" : "great match!", "title" : "Portugal vs. Denmark", }, "badge" : 1, }, "customKey" : "customValue" }
Gérer les messages avec le swizzling désactivé
Par défaut, si vous attribuez la classe déléguée à la classe
UNUserNotificationCenter
et Messaging
délèguent des propriétés, FCM
la classe déléguée de votre application pour associer automatiquement votre
Jeton FCM avec le jeton APNs de l'appareil et la notification de la carte reçue
les événements à Analytics. Si vous désactivez explicitement le swizzling,
créer une application SwiftUI, ou si vous utilisez une classe distincte pour l'un ou l'autre de ces délégués, vous
devra effectuer ces deux tâches manuellement.
Pour associer le jeton FCM au jeton APN de l'appareil, transmettez le jeton APN à la classe Messaging
dans le gestionnaire de renouvellement de jeton de votre délégué d'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 des informations de réception de notification à 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); }