Ricezione di messaggi nelle app della piattaforma Apple

Seleziona la piattaforma: iOS+ Android Web Flutter Unity C++


Una volta installata l'app client su un dispositivo, può ricevere messaggi tramite l'interfaccia APNs FCM. Puoi iniziare immediatamente a inviare notifiche ai segmenti di utenti con il compositore di notifiche, o messaggi creati sul server delle applicazioni.

Gestire le notifiche di avviso

FCM invia tutti i messaggi destinati alle app Apple tramite APNs. Per scoprire di più su come ricevere le notifiche APNs utilizzando UNUserNotificationCenter, consulta la documentazione di Apple su come gestire le notifiche e le azioni correlate alle notifiche.

Per ricevere le notifiche di visualizzazione da FCM, devi impostare il delegato UNUserNotificationCenter e implementare i metodi delegati appropriati.

Swift

// 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
  // Note: UNNotificationPresentationOptions.alert has been deprecated.
  return [.list, .banner, .sound]
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse) async {
  let userInfo = response.notification.request.content.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(UNNotificationPresentationOptionList |
                    UNNotificationPresentationOptionBanner |
                    UNNotificationPresentationOptionSound);
}

- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
    NSLog(@"FCM registration token: %@", fcmToken);
    // Notify about received token.
    NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];
    [[NSNotificationCenter defaultCenter] postNotificationName:
     @"FCMToken" object:nil userInfo:dataDict];
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}

- (void)logFCMToken {
  NSString *fcmToken = [FIRMessaging messaging].FCMToken;
  NSLog(@"Local FCM registration token: %@", fcmToken);

  NSString* displayToken = [NSString stringWithFormat:@"Logged FCM token: %@", fcmToken];

  [[FIRMessaging messaging] tokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
    if (error != nil) {
      NSLog(@"Error fetching the remote FCM registration token: %@", error);
    } else {
      NSLog(@"Remote FCM registration token: %@", token);
      NSString* message =
        [NSString stringWithFormat:@"FCM registration token: %@", token];
      // display message
      NSLog(@"%@", message);
    }
  }];
  NSLog(@"%@", displayToken);
}

- (void)subsribeToTopic {
  [[FIRMessaging messaging] subscribeToTopic:@"weather"
                                  completion:^(NSError * _Nullable error) {
    NSLog(@"Subscribed to weather topic");
  }];
}

@end

Se vuoi aggiungere azioni personalizzate alle notifiche, imposta il click_action parametro nel payload della notifica. Utilizza il valore che useresti per la chiave category nel payload APNs. Le azioni personalizzate devono essere registrate prima di poter essere utilizzate. Per saperne di più, consulta la Guida alla programmazione delle notifiche locali e remote di Apple .

Per informazioni sulla consegna dei messaggi alla tua app, consulta la FCM dashboard dei report, 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.

Gestire le notifiche push silenziose

Quando invii messaggi con la chiave content-available (equivalente a content-available di APNs), i messaggi verranno inviati 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 utilizzando il application(_:didReceiveRemoteNotification:fetchCompletionHandler:) metodo.

Implementa application(_:didReceiveRemoteNotification:fetchCompletionHandler:) come mostrato di seguito:

Swift

@MainActor
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 full message.
  print(userInfo)
  print("Call exportDeliveryMetricsToBigQuery() from AppDelegate")
  Messaging.serviceExtension().exportDeliveryMetricsToBigQuery(withMessageInfo: 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 until 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 scoprire di più sulle condizioni che possono causare il mancato invio delle notifiche in background, consulta la documentazione di Apple su come inviare aggiornamenti in background alla tua app.

Interpretare il payload del messaggio di notifica

Il payload dei messaggi di notifica è un dizionario di chiavi e valori. I messaggi di notifica inviati tramite APNs hanno il seguente formato di payload APNs:

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

Gestire i messaggi con lo swizzling dei metodi disattivato

Per impostazione predefinita, se assegni la classe del delegato dell'app alle proprietà del delegato UNUserNotificationCenter e Messaging, FCM eseguirà lo swizzling della classe del delegato dell'app per associare automaticamente il FCM token al token APNs del dispositivo e passare gli eventi di ricezione delle notifiche a Analytics. Se disattivi esplicitamente lo swizzling dei metodi, se stai creando un'app SwiftUI o se utilizzi una classe separata per uno dei due delegati, dovrai eseguire manualmente entrambe queste attività.

Per associare il FCM token al token APNs del dispositivo, passa il token APNs alla classe Messaging nel gestore di aggiornamento dei token del delegato dell'app utilizzando la apnsToken proprietà.

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

Per passare le informazioni sulla ricezione delle notifiche a Analytics, utilizza il appDidReceiveMessage(_:) metodo.

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