После установки клиентского приложения на устройство оно может получать сообщения через интерфейс FCM APNs. Вы можете немедленно начать отправлять уведомления сегментам пользователей с помощью Notifications composer или сообщений, созданных на сервере приложений.
Обработка оповещений
FCM доставляет все сообщения, нацеленные на приложения Apple, через APNs. Чтобы узнать больше о получении уведомлений APNs через UNUserNotificationCenter, см. документацию Apple по обработке уведомлений и действиям, связанным с уведомлениями .
Необходимо настроить делегат UNUserNotificationCenter и реализовать соответствующие методы делегата для получения уведомлений об отображении от FCM .
Быстрый
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(); }
Если вы хотите добавить пользовательские действия к уведомлениям, установите параметр click_action
в полезной нагрузке уведомления . Используйте значение, которое вы бы использовали для ключа category
в полезной нагрузке APNs. Пользовательские действия должны быть зарегистрированы, прежде чем их можно будет использовать. Для получения дополнительной информации см. Руководство по программированию локальных и удаленных уведомлений Apple.
Для получения более подробной информации о доставке сообщений в ваше приложение см. панель отчетов FCM , которая регистрирует количество отправленных и открытых сообщений на устройствах Apple и Android, а также данные о «показах» (уведомлениях, просмотренных пользователями) для приложений Android.
Обработка тихих push-уведомлений
При отправке сообщений с ключом content-available
(эквивалентным content-available
APNs) сообщения будут доставляться как тихие уведомления, активируя ваше приложение в фоновом режиме для таких задач, как фоновое обновление данных. В отличие от уведомлений переднего плана, эти уведомления должны обрабатываться с помощью метода application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
.
Реализуйте application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
, как показано:
Быстрый
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); }
Платформы Apple не гарантируют доставку фоновых уведомлений. Чтобы узнать об условиях, которые могут привести к сбою фоновых уведомлений, см. документы Apple по Pushing Background Updates to Your App .
Интерпретация полезной нагрузки уведомительного сообщения
Полезная нагрузка уведомительных сообщений — это словарь ключей и значений. Уведомительные сообщения, отправленные через APN, следуют формату полезной нагрузки APN, как показано ниже:
{ "aps" : { "alert" : { "body" : "great match!", "title" : "Portugal vs. Denmark", }, "badge" : 1, }, "customKey" : "customValue" }
Обработка сообщений с отключенным методом переключения
По умолчанию, если вы назначаете класс делегата приложения свойству делегата UNUserNotificationCenter
и Messaging
, FCM выполнит подмену вашего класса делегата приложения, чтобы автоматически связать ваш токен FCM с токеном APNs устройства и передать события получения уведомлений в Analytics . Если вы явно отключите подмену методов, если вы создаете приложение SwiftUI или используете отдельный класс для любого делегата, вам нужно будет выполнить обе эти задачи вручную.
Чтобы связать токен 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); }