Este guia descreve como configurar o Firebase Cloud Messaging nos seus apps cliente para dispositivos móveis e Web para que você possa receber mensagens de forma confiável.
Depois que o app cliente for instalado em um dispositivo, ele receberá mensagens pela interface de APNs do FCM. Você pode começar a enviar notificações imediatamente para segmentos de usuários com o Editor do Notificações ou mensagens criadas no seu servidor de aplicativos.
Gerenciar notificações de alerta
O FCM entrega todas as mensagens direcionadas aos apps da Apple por APNs. Para saber mais
sobre como receber notificações de APNs pelo UNUserNotificationCenter
, consulte a documentação
da Apple sobre
Como gerenciar notificações e ações relacionadas a notificações.
É necessário definir o delegado UNUserNotificationCenter e implementar os métodos delegados apropriados para receber notificações de exibição do FCM.
Swift
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();
}
Se você quiser adicionar ações personalizadas às notificações, defina o parâmetro
click_action
no
payload de notificação.
Use o valor utilizado para a chave
category
no payload de APNs.
As ações personalizadas precisam ser registradas antes
de serem usadas. Para ver mais informações, consulte o
Guia de programação de notificações locais e remotas da Apple.
Confira as informações sobre a entrega de mensagens ao seu app no painel de relatórios do FCM, que registra o número de mensagens enviadas e abertas em dispositivos Apple e Android, além de dados de "impressões" (notificações vistas pelos usuários) para apps Android.
Gerenciar notificações push silenciosas
Ao enviar mensagens com a chave content-available
(equivalente ao content-available
dos APNs), as mensagens serão entregues como notificações silenciosas,
ativando seu app em segundo plano para tarefas como atualização de dados em segundo plano.
Ao contrário das notificações em primeiro plano, elas precisam ser gerenciadas
pelo método
application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
.
Implemente application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
como mostrado:
Swift
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);
}
As plataformas da Apple não garantem a entrega de notificações em segundo plano. Para saber mais sobre as condições que podem causar falhas nas notificações em segundo plano, consulte os documentos da Apple sobre Como enviar atualizações em segundo plano ao app.
Interpretar o payload da mensagem de notificação
O payload das mensagens de notificação é um dicionário de chaves e valores. As mensagens de notificação enviadas com os APNs têm o seguinte formato de payload:
{
"aps" : {
"alert" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
},
"badge" : 1,
},
"customKey" : "customValue"
}
Gerenciar mensagens com o swizzling de métodos desativado
Por padrão, se você atribuir a classe delegada do seu app às propriedades delegadas
UNUserNotificationCenter
e Messaging
, o FCM
aplicará o swizzling à classe delegada do app para associar automaticamente
o token do FCM ao token de APNs do dispositivo e transmitir eventos de notificações
recebidas para o Analytics. Se você desativar explicitamente o swizzling de métodos, caso esteja criando
um app SwiftUI ou se usar uma classe separada para cada delegado, será
necessário executar as duas tarefas manualmente.
Para associar o token do FCM ao token de APNs do dispositivo, transmita esse
token para a classe Messaging
no
gerenciador de atualização de tokens do delegado do seu app usando a
propriedade 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;
}
Para transmitir informações de recebimento de notificações para Analytics, use o
método 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);
}