Ricevi messaggi in un'app Apple

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

Gestisci 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 delle azioni relative alle notifiche .

È necessario impostare il delegato UNUserNotificationCenter e implementare i metodi delegati appropriati per ricevere le notifiche di visualizzazione da FCM.

Rapido


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 vuoi aggiungere azioni personalizzate alle tue notifiche, imposta il parametro click_action nel payload delle notifiche . 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 sulla consegna dei messaggi alla tua app, consulta la 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 a content-available di APNs), i messaggi verranno consegnati 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:

Rapido

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 di notifiche in background. Per informazioni sulle condizioni che possono causare il fallimento delle notifiche in background, consulta i documenti 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 di seguito:

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

Gestisci i messaggi con lo scorrimento del metodo disabilitato

Per impostazione predefinita, se assegni la classe del delegato dell'app dell'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 trasmettere gli eventi ricevuti dalle notifiche ad Analytics. Se disabiliti in modo esplicito il metodo swizzling, se stai creando un'app SwiftUI o se utilizzi una classe separata per uno dei due delegati, dovrai eseguire entrambe queste attività manualmente.

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

Rapido

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(_:) .

Rapido

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