Odbieranie wiadomości w aplikacji Apple

Po zainstalowaniu aplikacji klienckiej na urządzeniu może ona odbierać wiadomości przez w interfejsie APNs w FCM. Możesz od razu rozpocząć wysyłania powiadomień do segmentów użytkowników z Kreator powiadomień lub wiadomości utworzone na serwera aplikacji.

Obsługa powiadomień o alertach

FCM dostarcza wszystkie wiadomości kierowane na aplikacje Apple przy użyciu punktów APN. Więcej informacji o otrzymywaniu powiadomień APNs za pośrednictwem UNUsernotificationCenter, zapoznaj się z dokumentacja dotycząca Obsługa powiadomień i działań związanych z powiadomieniami

Musisz ustawić parametr Przedstawiciel UNUserPowiadomCenter i wdrażaj odpowiednie metody przekazywania powiadomień, od 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();
}

Jeśli chcesz dodać do powiadomień działania niestandardowe, ustaw click_action w ładunek powiadomień. Użyj wartości, której użyjesz jako parametru category w ładunku APNs. Działania niestandardowe należy zarejestrować przed i ich zastosowania. Więcej informacji znajdziesz w Lokalny i zdalny przewodnik po programowaniu powiadomień.

Więcej informacji o dostarczaniu wiadomości do aplikacji znajdziesz tutaj: panelu raportowania FCM, który rejestruje liczba wiadomości wysłanych i otwartych na urządzeniach Apple i z Androidem oraz dane dotyczące „wyświetleń” (powiadomienia użytkowników) dotyczące aplikacji na Androida.

Obsługa cichych powiadomień push

Podczas wysyłania wiadomości za pomocą klucza content-available (odpowiedniego klucza APNs content-available, wiadomości będą dostarczane jako powiadomienia ciche, wybudzanie aplikacji w tle w celu wykonania takich zadań jak odświeżanie danych w tle; W przeciwieństwie do powiadomień działających na pierwszym planie powiadomienia te muszą być obsługiwane za pomocą application(_:didReceiveRemoteNotification:fetchCompletionHandler:) .

Wdróż application(_:didReceiveRemoteNotification:fetchCompletionHandler:) Jak widać:

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

Platformy Apple nie gwarantują dostarczania powiadomień w tle. Aby dowiedzieć się więcej o: mogące powodować błędy powiadomień w tle, zapoznaj się z dokumentacją Apple Przekazywanie aktualizacji aplikacji w tle.

Interpretowanie ładunku wiadomości z powiadomieniem

Ładunek wiadomości z powiadomieniami to słownik kluczy i wartości. Wiadomości z powiadomieniami wysyłane przez APNs są zgodne z punktami APN jak w poniższym formacie:

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

Obsługa wiadomości z wyłączonym przesuwaniem metod

Domyślnie, jeśli przypiszesz klasę do przekazywania dostępu do aplikacji do Właściwości przedstawiciela UNUserNotificationCenter i Messaging, FCM klasa przedstawiciela aplikacji będzie wibrować, aby automatycznie powiązać Twoją Token FCM z tokenem APNs urządzenia i otrzymano powiadomienie zdarzeń do Analytics. Jeśli wyraźnie wyłączysz przesuwanie metod, tworząc aplikację SwiftUI. A jeśli używasz osobnej klasy dla jednego z przedstawicieli, będzie musiał wykonać obie te czynności ręcznie.

Aby powiązać token FCM z tokenem APNs urządzenia, przekaż APNs token do klasy Messaging w urzędzie delegata aplikacji obsługa odświeżania tokena przez Usługa: 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;
}

Aby przekazywać do Analytics informacje o rachunkach powiadomień, skorzystaj z metody Metoda 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);
}