Ricevere messaggi in un'app Apple

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

Gestire le notifiche di avviso

FCM recapita tutti i messaggi che hanno come target le app Apple tramite APN. Per saperne di più sulla ricezione di notifiche APN tramite UNUserNotificationCenter, consulta la documentazione di Apple su Gestione di notifiche e azioni correlate alle notifiche.

Devi impostare il delegato UNUserNotificationCenter e implementare i metodi delegati appropriati per ricevere notifiche di visualizzazione da 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();
}

Se vuoi aggiungere azioni personalizzate alle tue notifiche, imposta il parametro click_action 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 distribuzione dei messaggi alla tua app, consulta la dashboard dei report FCM, che registra il numero di messaggi inviati e aperti su dispositivi Apple e Android, nonché i dati relativi alle "impressioni" (notifiche visualizzate dagli utenti) per le app per Android.

Gestire le notifiche push silenziose

Quando invii messaggi con il tasto content-available (equivalente a content-available di 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 il metodo application(_:didReceiveRemoteNotification:fetchCompletionHandler:).

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

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

Le piattaforme Apple non garantiscono la ricezione delle notifiche in background. Per scoprire di più sulle condizioni che possono causare l'errore delle notifiche in background, consulta la documentazione di Apple su Pushing Background Updates to Your App.

Interpretazione del payload del messaggio di notifica

Il payload dei messaggi di notifica è un dizionario di chiavi e valori. I messaggi di notifica inviati tramite APN seguono il formato del payload APN come indicato di seguito:

  {
    "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 delegata dell'app alle proprietà delegate UNUserNotificationCenter e Messaging, FCM esegue lo swizzle della classe delegata dell'app per associare automaticamente il token FCM al token APNs del dispositivo e trasmettere 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 delegati, dovrai eseguire manualmente entrambe queste attività.

Per associare il token FCM al token APNs del dispositivo, passa il token APNs alla classe Messaging nel gestore di aggiornamento dei token del delegato dell'app tramite la proprietà 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;
}

Per trasmettere a Analytics le informazioni sulla ricezione delle notifiche, utilizza il metodo 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);
}