Una volta installata l'app client su un dispositivo, è possibile ricevere messaggi tramite l'interfaccia APN di FCM. Puoi iniziare immediatamente a inviare notifiche a segmenti di utenti con il compositore di notifiche o messaggi creati sul tuo server delle applicazioni.
Gestire le notifiche di avviso
FCM consegna tutti i messaggi destinati alle app Apple tramite APN. Per ulteriori informazioni sulla ricezione delle notifiche APN tramite UNUserNotificationCenter, consulta la documentazione di Apple sulla gestione delle notifiche e sulle azioni relative alle notifiche .
È necessario impostare il delegato UNUserNotificationCenter e implementare i metodi delegati appropriati per ricevere notifiche di visualizzazione da FCM.
Veloce
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) } }
Obiettivo-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(); }
Se desideri aggiungere azioni personalizzate alle tue notifiche, imposta il parametro click_action
nel payload della notifica . Utilizza il valore che utilizzeresti per la chiave category
nel payload APN. Le azioni personalizzate devono essere registrate prima di poter essere utilizzate. Per ulteriori informazioni, consulta la Guida alla programmazione delle notifiche locali e remote di Apple.
Per informazioni dettagliate sulla consegna dei messaggi alla tua app, consulta il dashboard dei rapporti FCM , che registra il numero di messaggi inviati e aperti su dispositivi Apple e Android, insieme ai dati per le "impressioni" (notifiche visualizzate dagli utenti) per le app Android.
Gestisci le notifiche push silenziose
Quando si inviano messaggi con la chiave content_available
(equivalente alla chiave content-available
degli APN, i messaggi verranno recapitati come notifiche silenziose, riattivando l'app in background per attività come l'aggiornamento dei dati in background. A differenza delle notifiche in primo piano, queste notifiche devono essere gestite tramite l' application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
metodo.
Implementa application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
come mostrato:
Veloce
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 }
Obiettivo-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); }
Le piattaforme Apple non garantiscono la consegna delle notifiche in background. Per informazioni sulle condizioni che possono causare il fallimento delle notifiche in background, consulta i documenti di Apple sull'invio di aggiornamenti in background alla tua app .
Interpretazione del payload del messaggio di notifica
Il carico utile dei messaggi di notifica è un dizionario di chiavi e valori. I messaggi di notifica inviati tramite gli APN seguono il formato del payload degli APN come di seguito:
{ "aps" : { "alert" : { "body" : "great match!", "title" : "Portugal vs. Denmark", }, "badge" : 1, }, "customKey" : "customValue" }
Gestisci i messaggi con il metodo swizzling disabilitato
Per impostazione predefinita, se assegni la classe del delegato dell'app della tua app alle proprietà del delegato UNUserNotificationCenter
e Messaging
, FCM farà scorrere la classe del delegato dell'app per associare automaticamente il token FCM al token APN del dispositivo e passare gli eventi ricevuti dalle notifiche ad Analytics. Se disabiliti esplicitamente lo swizzling del metodo, se stai creando un'app SwiftUI o se utilizzi una classe separata per uno dei delegati, dovrai eseguire entrambe queste attività manualmente.
Per associare il token FCM al token APN del dispositivo, passa il token APN alla classe Messaging
nel gestore di aggiornamento del token del delegato dell'app tramite la proprietà apnsToken
.
Veloce
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Messaging.messaging().apnsToken = deviceToken; }
Obiettivo-C
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [FIRMessaging messaging].APNSToken = deviceToken; }
Per trasmettere le informazioni sulla ricezione della notifica ad Analytics, utilizza il metodo appDidReceiveMessage(_:)
.
Veloce
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) }
Obiettivo-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); }