Как только ваше клиентское приложение установлено на устройстве, оно может получать сообщения через интерфейс FCM APN. Вы можете сразу же начать отправлять уведомления сегментам пользователей с помощью компоновщика уведомлений или сообщений, созданных на вашем сервере приложений.
Обработка предупреждений
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) } }
Цель-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
в полезной нагрузке APN. Пользовательские действия должны быть зарегистрированы, прежде чем их можно будет использовать. Дополнительные сведения см. в Руководстве Apple по программированию локальных и удаленных уведомлений .
Чтобы получить представление о доставке сообщений в ваше приложение, см. информационную панель отчетности FCM , которая записывает количество сообщений, отправленных и открытых на устройствах Apple и Android, а также данные о «показах» (уведомлениях, просмотренных пользователями) для приложений Android.
Обработка тихих push-уведомлений
При отправке сообщений с помощью ключа content_available
(эквивалентно content-available
в APN, сообщения будут доставляться как тихие уведомления, пробуждая ваше приложение в фоновом режиме для таких задач, как фоновое обновление данных. В отличие от уведомлений переднего плана, эти уведомления должны обрабатываться через 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 }
Цель-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, следуют формату полезной нагрузки APN, как показано ниже:
{ "aps" : { "alert" : { "body" : "great match!", "title" : "Portugal vs. Denmark", }, "badge" : 1, }, "customKey" : "customValue" }
Обрабатывать сообщения с отключенным просмотром методов
По умолчанию, если вы назначите класс делегата приложения своего приложения свойствам делегата UNUserNotificationCenter
и Messaging
, FCM изменит класс делегата вашего приложения, чтобы автоматически связать ваш токен FCM с токеном APN устройства и передать полученные уведомления о событиях в Analytics. Если вы явно отключите смену методов, если вы создаете приложение SwiftUI или если вы используете отдельный класс для любого делегата, вам нужно будет выполнить обе эти задачи вручную.
Чтобы связать токен FCM с токеном APN устройства, передайте токен APNs в класс Messaging
в обработчике обновления токена делегата вашего приложения через свойство apnsToken
.
Быстрый
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Messaging.messaging().apnsToken = deviceToken; }
Цель-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) }
Цель-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); }