Odbieraj wiadomości w aplikacji Apple

Po zainstalowaniu aplikacji klienckiej na urządzeniu może ona odbierać wiadomości za pośrednictwem interfejsu APN FCM. Możesz natychmiast rozpocząć wysyłanie powiadomień do segmentów użytkowników za pomocą narzędzia do tworzenia powiadomień lub wiadomości zbudowanych na serwerze aplikacji.

Obsługuj powiadomienia o alertach

FCM dostarcza wszystkie wiadomości kierowane do aplikacji Apple za pośrednictwem APN. Aby dowiedzieć się więcej na temat otrzymywania powiadomień APN za pośrednictwem UNUserNotificationCenter, zapoznaj się z dokumentacją firmy Apple dotyczącą obsługi powiadomień i działań związanych z powiadomieniami .

Aby otrzymywać powiadomienia o wyświetlaniu z FCM, należy ustawić delegata UNUserNotificationCenter i zaimplementować odpowiednie metody delegowania.

Szybki


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

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

Jeśli chcesz dodać niestandardowe akcje do swoich powiadomień, ustaw parametr click_action w ładunku powiadomienia . Użyj wartości, której użyłbyś dla klucza category w ładunku APNs. Akcje niestandardowe muszą zostać zarejestrowane, zanim będzie można ich użyć. Więcej informacji można znaleźć w Przewodniku programowania powiadomień lokalnych i zdalnych firmy Apple.

Wgląd w dostarczanie wiadomości do aplikacji znajdziesz w panelu raportowania FCM , który rejestruje liczbę wiadomości wysłanych i otwartych na urządzeniach Apple i Android, wraz z danymi dotyczącymi „wyświetleń” (powiadomień widocznych przez użytkowników) w przypadku aplikacji na Androida.

Obsługuj ciche powiadomienia push

Podczas wysyłania wiadomości z kluczem content_available (odpowiednik klucza APNs content-available , wiadomości będą dostarczane jako ciche powiadomienia, budząc aplikację w tle w celu wykonania takich zadań, jak odświeżanie danych w tle. W przeciwieństwie do powiadomień na pierwszym planie, powiadomienia te muszą być obsługiwane przez application(_:didReceiveRemoteNotification:fetchCompletionHandler:) metoda.

Zaimplementuj application(_:didReceiveRemoteNotification:fetchCompletionHandler:) jak pokazano:

Szybki

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
}

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

Platformy Apple nie gwarantują dostarczania powiadomień w tle. Aby dowiedzieć się o warunkach, które mogą powodować niepowodzenie powiadomień w tle, zapoznaj się z dokumentacją firmy Apple dotyczącą przekazywania aktualizacji w tle do aplikacji .

Interpretowanie ładunku komunikatu powiadomienia

Ładunek komunikatów powiadomień to słownik kluczy i wartości. Powiadomienia wysyłane za pośrednictwem APN mają następujący format ładunku APN:

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

Obsługuj komunikaty z wyłączoną zmianą metody

Domyślnie, jeśli przypiszesz klasę delegata aplikacji do właściwości delegata UNUserNotificationCenter i Messaging , FCM zamieni klasę delegata aplikacji, aby automatycznie powiązać token FCM z tokenem APN urządzenia i przekazywać zdarzenia otrzymane z powiadomieniami do Analytics. Jeśli jawnie wyłączysz zmianę metody, jeśli tworzysz aplikację SwiftUI lub jeśli używasz osobnej klasy dla któregokolwiek delegata, będziesz musiał wykonać oba te zadania ręcznie.

Aby powiązać token FCM z tokenem APNs urządzenia, przekaż token APNs do klasy Messaging w procedurze obsługi odświeżania tokenu delegata aplikacji za pośrednictwem właściwości apnsToken .

Szybki

func application(_ application: UIApplication,
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  Messaging.messaging().apnsToken = deviceToken;
}
 

Cel C

- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [FIRMessaging messaging].APNSToken = deviceToken;
}

Aby przekazać informacje o otrzymaniu powiadomienia do Analytics, użyj metody appDidReceiveMessage(_:) .

Szybki

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

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