Sulla base del modello di pubblicazione/sottoscrizione, la messaggistica degli argomenti FCM consente di inviare un messaggio a più dispositivi che hanno aderito a un determinato argomento. Componi i messaggi degli argomenti secondo necessità e FCM gestisce l'instradamento e la consegna del messaggio in modo affidabile ai dispositivi giusti.
Ad esempio, gli utenti di un'app locale per la previsione delle maree potrebbero scegliere un argomento "avvisi sulle correnti di marea" e ricevere notifiche sulle condizioni ottimali per la pesca in acqua salata in aree specifiche. Gli utenti di un'app per lo sport possono iscriversi agli aggiornamenti automatici dei risultati delle partite in diretta per le loro squadre preferite.
Alcune cose da tenere a mente sugli argomenti:
- La messaggistica dell'argomento è più adatta per contenuti come meteo o altre informazioni disponibili pubblicamente.
- I messaggi dell'argomento sono ottimizzati per la velocità effettiva anziché per la latenza . Per un recapito rapido e sicuro a singoli dispositivi o piccoli gruppi di dispositivi, indirizza i messaggi ai token di registrazione , non agli argomenti.
- Se devi inviare messaggi a più dispositivi per utente , prendi in considerazione la messaggistica del gruppo di dispositivi per questi casi d'uso.
- La messaggistica degli argomenti supporta abbonamenti illimitati per ciascun argomento. Tuttavia, FCM impone limiti in queste aree:
- Un'istanza dell'app può essere sottoscritta a non più di 2000 argomenti.
- Se utilizzi l'importazione batch per sottoscrivere le istanze dell'app, ogni richiesta è limitata a 1000 istanze dell'app.
- La frequenza dei nuovi abbonamenti è limitata alla tariffa per progetto. Se invii troppe richieste di sottoscrizione in un breve periodo di tempo, i server FCM risponderanno con una risposta
429 RESOURCE_EXHAUSTED
("quota superata"). Riprova con backoff esponenziale.
Sottoscrivere l'app client a un argomento
Le app client possono iscriversi a qualsiasi argomento esistente oppure possono creare un nuovo argomento. Quando un'app client si iscrive a un nuovo nome di argomento (uno che non esiste già per il tuo progetto Firebase), viene creato un nuovo argomento con quel nome in FCM e qualsiasi client può successivamente sottoscriverlo.
Per sottoscrivere un argomento, chiama il metodo di sottoscrizione dal thread principale della tua applicazione (FCM non è thread-safe). Se inizialmente la richiesta di sottoscrizione non riesce, FCM riprova automaticamente. Per i casi in cui l'abbonamento non può essere completato, l'abbonamento genera un errore che puoi rilevare in un gestore di completamento come mostrato:
Rapido
Messaging.messaging().subscribe(toTopic: "weather") { error in print("Subscribed to weather topic") }
Obiettivo-C
[[FIRMessaging messaging] subscribeToTopic:@"weather" completion:^(NSError * _Nullable error) { NSLog(@"Subscribed to weather topic"); }];
Questa chiamata effettua una richiesta asincrona al backend FCM e iscrive il client all'argomento specificato. Prima di chiamare subscribeToTopic:topic
, assicurati che l'istanza dell'app client abbia già ricevuto un token di registrazione tramite il callback didReceiveRegistrationToken
.
Ogni volta che l'app viene avviata, FCM si assicura che tutti gli argomenti richiesti siano stati sottoscritti. Per annullare l'iscrizione, chiama unsubscribeFromTopic:topic
e FCM annulla l'iscrizione all'argomento in background.
Gestisci gli abbonamenti agli argomenti sul server
L' SDK Firebase Admin ti consente di eseguire attività di gestione degli argomenti di base dal lato server. Dati i token di registrazione, è possibile sottoscrivere e annullare la sottoscrizione alle istanze dell'app client in blocco utilizzando la logica del server.
Puoi sottoscrivere le istanze dell'app client a qualsiasi argomento esistente oppure puoi creare un nuovo argomento. Quando utilizzi l'API per iscrivere un'app client a un nuovo argomento (uno che non esiste già per il tuo progetto Firebase), viene creato un nuovo argomento con quel nome in FCM e qualsiasi client può successivamente sottoscriverlo.
Puoi passare un elenco di token di registrazione al metodo di sottoscrizione dell'SDK Firebase Admin per sottoscrivere i dispositivi corrispondenti a un argomento:
Node.js
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// ...
'YOUR_REGISTRATION_TOKEN_n'
];
// Subscribe the devices corresponding to the registration tokens to the
// topic.
getMessaging().subscribeToTopic(registrationTokens, topic)
.then((response) => {
// See the MessagingTopicManagementResponse reference documentation
// for the contents of response.
console.log('Successfully subscribed to topic:', response);
})
.catch((error) => {
console.log('Error subscribing to topic:', error);
});
Giava
// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n"
);
// Subscribe the devices corresponding to the registration tokens to the
// topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopic(
registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were subscribed successfully");
Pitone
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
'YOUR_REGISTRATION_TOKEN_1',
# ...
'YOUR_REGISTRATION_TOKEN_n',
]
# Subscribe the devices corresponding to the registration tokens to the
# topic.
response = messaging.subscribe_to_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were subscribed successfully')
Andare
// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
}
// Subscribe the devices corresponding to the registration tokens to the
// topic.
response, err := client.SubscribeToTopic(ctx, registrationTokens, topic)
if err != nil {
log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were subscribed successfully")
C#
// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
};
// Subscribe the devices corresponding to the registration tokens to the
// topic
var response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(
registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were subscribed successfully");
L'API Admin FCM consente inoltre di annullare l'iscrizione dei dispositivi a un argomento passando i token di registrazione al metodo appropriato:
Node.js
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// ...
'YOUR_REGISTRATION_TOKEN_n'
];
// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
getMessaging().unsubscribeFromTopic(registrationTokens, topic)
.then((response) => {
// See the MessagingTopicManagementResponse reference documentation
// for the contents of response.
console.log('Successfully unsubscribed from topic:', response);
})
.catch((error) => {
console.log('Error unsubscribing from topic:', error);
});
Giava
// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n"
);
// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().unsubscribeFromTopic(
registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were unsubscribed successfully");
Pitone
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
'YOUR_REGISTRATION_TOKEN_1',
# ...
'YOUR_REGISTRATION_TOKEN_n',
]
# Unubscribe the devices corresponding to the registration tokens from the
# topic.
response = messaging.unsubscribe_from_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were unsubscribed successfully')
Andare
// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
}
// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
response, err := client.UnsubscribeFromTopic(ctx, registrationTokens, topic)
if err != nil {
log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were unsubscribed successfully")
C#
// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
};
// Unsubscribe the devices corresponding to the registration tokens from the
// topic
var response = await FirebaseMessaging.DefaultInstance.UnsubscribeFromTopicAsync(
registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were unsubscribed successfully");
I metodi subscribeToTopic()
e unsubscribeFromTopic()
danno come risultato un oggetto contenente la risposta di FCM. Il tipo restituito ha lo stesso formato indipendentemente dal numero di token di registrazione specificati nella richiesta.
In caso di errore (errore di autenticazione, token o argomento non valido ecc.) questi metodi generano un errore. Per un elenco completo dei codici di errore, comprese le descrizioni e i passaggi per la risoluzione, vedere Errori dell'API FCM di amministrazione .
Ricevere e gestire i messaggi di argomento
FCM consegna i messaggi topic allo stesso modo degli altri messaggi downstream.
Implementa application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
come mostrato:
Rapido
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 }
Obiettivo-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); }
Crea richieste di invio
Dopo aver creato un argomento, sottoscrivendo le istanze dell'app client all'argomento sul lato client o tramite l' API del server , puoi inviare messaggi all'argomento. Se è la prima volta che crei richieste di invio per FCM, consulta la guida al tuo ambiente server e FCM per importanti informazioni di base e di configurazione.
Nella tua logica di invio sul back-end, specifica il nome dell'argomento desiderato come mostrato:
Node.js
// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';
const message = {
data: {
score: '850',
time: '2:45'
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Giava
// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setTopic(topic)
.build();
// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
Pitone
# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'
# See documentation on defining a message payload.
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
topic=topic,
)
# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
Andare
// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Topic: topic,
}
// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
C#
// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";
// See documentation on defining a message payload.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
Topic = topic,
};
// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
RIPOSO
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"topic" : "foo-bar",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message"
}
}
}
comando URL:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message": {
"topic" : "foo-bar",
"notification": {
"body": "This is a Firebase Cloud Messaging Topic Message!",
"title": "FCM Message"
}
}
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Per inviare un messaggio a una combinazione di argomenti, specifica una condizione , che è un'espressione booleana che specifica gli argomenti di destinazione. Ad esempio, la seguente condizione invierà messaggi ai dispositivi che sono iscritti a TopicA
e TopicB
o TopicC
:
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM prima valuta tutte le condizioni tra parentesi, quindi valuta l'espressione da sinistra a destra. Nell'espressione precedente, un utente iscritto a un singolo argomento non riceve il messaggio. Allo stesso modo, un utente che non si iscrive a TopicA
non riceve il messaggio. Queste combinazioni lo ricevono:
-
TopicA
eTopicB
-
TopicA
eTopicC
Puoi includere fino a cinque argomenti nell'espressione condizionale.
Per inviare a una condizione:
Node.js
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';
// See documentation on defining a message payload.
const message = {
notification: {
title: '$FooCorp up 1.43% on the day',
body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
},
condition: condition
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Giava
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
Message message = Message.builder()
.setNotification(Notification.builder()
.setTitle("$GOOG up 1.43% on the day")
.setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
.build())
.setCondition(condition)
.build();
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
Pitone
# Define a condition which will send to devices which are subscribed
# to either the Google stock or the tech industry topics.
condition = "'stock-GOOG' in topics || 'industry-tech' in topics"
# See documentation on defining a message payload.
message = messaging.Message(
notification=messaging.Notification(
title='$GOOG up 1.43% on the day',
body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
),
condition=condition,
)
# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
Andare
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
condition := "'stock-GOOG' in topics || 'industry-tech' in topics"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Condition: condition,
}
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
C#
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
var message = new Message()
{
Notification = new Notification()
{
Title = "$GOOG up 1.43% on the day",
Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
},
Condition = condition,
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
RIPOSO
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"condition": "'dogs' in topics || 'cats' in topics",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message",
}
}
}
comando URL:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"notification": {
"title": "FCM Message",
"body": "This is a Firebase Cloud Messaging Topic Message!",
},
"condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Prossimi passi
- Scopri di più sull'altro modo per inviare a più dispositivi: messaggistica di gruppo di dispositivi