| Выберите платформу: | iOS+ Android Веб Flutter Unity C++ |
После установки клиентского приложения на устройство оно может получать сообщения через интерфейс APNs FCM. Вы можете сразу начать отправлять уведомления сегментам пользователей с помощью конструктора уведомлений в консоли Firebase или сообщений, созданных на сервере приложений.
Как обрабатывать уведомления об оповещениях
FCM доставляет все сообщения, предназначенные для приложений Apple, через APNs. Чтобы узнать больше о получении уведомлений APNs с помощью UNUserNotificationCenter, ознакомьтесь с документацией Apple о том, как обрабатывать уведомления и связанные с ними действия.
Чтобы получать уведомления от FCM, необходимо задать делегата UNUserNotificationCenter и реализовать соответствующие методы делегата.
Swift
// 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.
Чтобы узнать, как сообщения доставляются в ваше приложение, откройте раздел DevOps и вовлеченность > Обмен сообщениями > Отчеты на панели управления Firebase. На этой панели управления регистрируется количество сообщений, отправленных и открытых на устройствах Apple и Android, а также данные о показах (уведомлениях, которые видели пользователи) для приложений Android.
Как обрабатывать беззвучные push-уведомления
При отправке сообщений с ключом content-available (эквивалент ключа content-available в APNs) сообщения будут доставляться как беззвучные уведомления, которые активируют приложение в фоновом режиме для выполнения таких задач, как обновление данных.
В отличие от уведомлений, которые показываются, когда приложение открыто, эти уведомления должны обрабатываться с помощью метода application(_:didReceiveRemoteNotification:fetchCompletionHandler:).
Реализуйте application(_:didReceiveRemoteNotification:fetchCompletionHandler:), как показано ниже:
Swift
@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 в разделе Pushing Background Updates to Your App (Отправка фоновых обновлений в приложение).
Как интерпретировать полезную нагрузку уведомления
Полезная нагрузка уведомлений представляет собой словарь ключей и значений. Уведомления, отправляемые через APNs, имеют следующий формат полезной нагрузки APNs:
{
"aps" : {
"alert" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
},
"badge" : 1,
},
"customKey" : "customValue"
}
Как обрабатывать сообщения при отключенном методе swizzling
По умолчанию, если вы назначите класс делегата приложения свойствам делегата UNUserNotificationCenter и Messaging, FCM будет подменять класс делегата приложения, чтобы автоматически связать токен FCM с токеном APNs устройства и передавать события получения уведомлений в Analytics. Если вы явно отключили подмену методов, создаете приложение SwiftUI или используете отдельный класс для любого из делегатов, вам нужно будет выполнить обе эти задачи вручную.
Чтобы связать токен FCM с токеном APNs устройства, передайте токен APNs классу Messaging в обработчике обновления токена делегата приложения, используя свойство 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;
}
Чтобы передать информацию о получении уведомления в Analytics, используйте метод 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);
}