Получайте сообщения в приложениях платформы Apple.

Выберите платформу: iOS+ Android Web Flutter Unity C++


После установки клиентского приложения на устройство оно сможет получать сообщения через интерфейс FCM APNs. Вы можете немедленно начать отправлять уведомления сегментам пользователей с помощью редактора уведомлений или сообщения, созданные на вашем сервере приложений.

Обработка уведомлений о тревогах

FCM доставляет все сообщения, предназначенные для приложений Apple, через APNs. Чтобы узнать больше о получении уведомлений APNs с помощью UNUserNotificationCenter , см. документацию Apple по обработке уведомлений и действиям, связанным с уведомлениями .

Для получения уведомлений от FCM необходимо установить делегат UNUserNotificationCenter и реализовать соответствующие методы делегата.

Быстрый

// 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

Если вы хотите добавить пользовательские действия к своим уведомлениям, установите параметр click_action в полезной нагрузке уведомления . Используйте значение, которое вы бы использовали для ключа category в полезной нагрузке APNs. Пользовательские действия должны быть зарегистрированы, прежде чем их можно будет использовать. Для получения дополнительной информации см. Руководство Apple по программированию локальных и удаленных уведомлений .

Для получения информации о доставке сообщений в ваше приложение, ознакомьтесь с панелью отчетов FCM , которая регистрирует количество отправленных и открытых сообщений на устройствах Apple и Android, а также данные о «показах» (уведомлениях, просмотренных пользователями) для приложений Android.

Обработка бесшумных push-уведомлений

При отправке сообщений с ключом content-available (эквивалентным ключу content-available в APNs) сообщения будут доставляться в виде бесшумных уведомлений, пробуждая ваше приложение в фоновом режиме для выполнения таких задач, как фоновое обновление данных. В отличие от уведомлений переднего плана, эти уведомления должны обрабатываться с помощью метода application(_:didReceiveRemoteNotification:fetchCompletionHandler:) .

Реализуйте функцию application(_:didReceiveRemoteNotification:fetchCompletionHandler:) , как показано ниже:

Быстрый

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

Платформы Apple не гарантируют доставку фоновых уведомлений. Чтобы узнать о причинах, которые могут привести к сбою фоновых уведомлений, см. документацию Apple по отправке фоновых обновлений в ваше приложение .

Интерпретация содержимого уведомления

В состав полезной нагрузки уведомлений входит словарь ключей и значений. Уведомления, отправляемые через APNs, имеют следующий формат полезной нагрузки APNs:

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

Обработка сообщений с отключенной возможностью подмены методов.

By default, if you assign your app's app delegate class to the UNUserNotificationCenter and Messaging delegate properties, FCM will swizzle your app delegate class to automatically associate your FCM token with the device's APNs token and pass notification-received events to Analytics . If you explicitly disable method swizzling, if you are building a SwiftUI app, or if you use a separate class for either delegate, you will need to perform both of these tasks manually.

Чтобы связать токен FCM с токеном APNs устройства, передайте токен APNs классу Messaging в обработчике обновления токена вашего делегата приложения, используя свойство apnsToken .

Быстрый

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

Objective-C

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

Для передачи информации о получении уведомления в Analytics используйте метод appDidReceiveMessage(_:) .

Быстрый

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