После установки клиентского приложения на устройство оно сможет получать сообщения через интерфейс FCM APNs. Вы можете сразу начать отправлять уведомления определённым сегментам пользователей с помощью редактора уведомлений или сообщений, созданных на сервере приложений.
Обработка оповещений
FCM доставляет все сообщения, адресованные приложениям Apple, через APN. Подробнее о получении уведомлений APN через 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 по отправке фоновых обновлений в приложение .
Интерпретация полезной нагрузки уведомительного сообщения
Полезная нагрузка уведомлений представляет собой словарь ключей и значений. Уведомления, отправляемые через 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); }