| Wybierz platformę: | iOS+ Android Web Flutter Unity C++ |
Po zainstalowaniu aplikacji klienckiej na urządzeniu może ona odbierać wiadomości przez interfejs APNs FCM. Możesz od razu zacząć wysyłać powiadomienia do segmentów użytkowników za pomocą Kreatora powiadomień w konsoli Firebase lub wiadomości utworzonych na serwerze aplikacji.
Obsługa powiadomień o alertach
FCM dostarcza wszystkie wiadomości kierowane na aplikacje Apple przez APNs. Więcej informacji o odbieraniu powiadomień APNs za pomocą UNUserNotificationCenter znajdziesz w dokumentacji Apple dotyczącej obsługi powiadomień i działań związanych z powiadomieniami.
Aby otrzymywać powiadomienia z FCM, musisz ustawić UNUserNotificationCenter delegate i zaimplementować odpowiednie metody delegowania.
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
Jeśli chcesz dodać do powiadomień działania niestandardowe, ustaw parametr click_action w ładunku powiadomienia.
Użyj wartości, której używasz w przypadku klucza category w ładunku APNs.
Działania niestandardowe muszą zostać zarejestrowane, zanim będzie można ich używać. Więcej informacji znajdziesz w przewodniku Apple dotyczącym programowania powiadomień lokalnych i zdalnych.
Aby uzyskać statystyki dotyczące dostarczania wiadomości do aplikacji, otwórz panel DevOps & Engagement (DevOps i zaangażowanie) > Messaging (Przesyłanie wiadomości) > Reports (Raporty) w konsoli Firebase. Ten panel rejestruje liczbę wiadomości wysłanych i otwartych na urządzeniach Apple i urządzeniach z Androidem, a także dane dotyczące „wyświetleń” (powiadomień wyświetlonych użytkownikom) w aplikacjach na Androida.
Obsługa cichych powiadomień push
Gdy wysyłasz wiadomości z kluczem content-available (odpowiednik content-available w APNs), wiadomości będą dostarczane jako ciche powiadomienia, które wybudzają aplikację w tle, aby wykonać zadania takie jak odświeżanie danych w tle.
W przeciwieństwie do powiadomień na pierwszym planie te powiadomienia muszą być obsługiwane za pomocą metody application(_:didReceiveRemoteNotification:fetchCompletionHandler:).
Zaimplementuj application(_:didReceiveRemoteNotification:fetchCompletionHandler:) w ten sposób:
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);
}
Platformy Apple nie gwarantują dostarczania powiadomień w tle. Aby dowiedzieć się więcej o warunkach, które mogą powodować błędy powiadomień w tle, zapoznaj się z dokumentacją Apple dotyczącą wysyłania aktualizacji w tle do aplikacji.
Interpretowanie ładunku wiadomości z powiadomieniem
Ładunek powiadomień to słownik kluczy i wartości. Wiadomości z powiadomieniem wysyłane przez APNs mają ten format danych:
{
"aps" : {
"alert" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
},
"badge" : 1,
},
"customKey" : "customValue"
}
Obsługa wiadomości z wyłączoną podmianą metody
Domyślnie, jeśli przypiszesz klasę delegata aplikacji do właściwości delegata UNUserNotificationCenter i Messaging, FCM podmieni klasę delegata aplikacji, aby automatycznie powiązać token FCM z tokenem APN urządzenia i przekazywać zdarzenia odebrania powiadomienia do Analytics. Jeśli wyraźnie wyłączysz podmianę metody, tworzysz aplikację SwiftUI lub używasz osobnej klasy dla któregoś z obiektów delegowanych, musisz wykonać oba te zadania ręcznie.
Aby powiązać token FCM z tokenem APNs urządzenia, przekaż token APNs do klasy Messaging w procedurze obsługi odświeżania tokena delegata aplikacji za pomocą właściwości 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;
}
Aby przekazać informacje o otrzymaniu powiadomienia do Analytics, użyj metody 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);
}