Gestire le iscrizioni agli argomenti

Puoi iscrivere un'app client a un argomento dal server o dal client:

  • Sul server, utilizzando Firebase Admin SDK.

  • Sul client, utilizzando l'API lato client all'interno dell'app.

Gestire le iscrizioni agli argomenti utilizzando l'SDK Admin

Firebase Admin SDK ti consente di eseguire attività di gestione di base degli argomenti dal lato server. Dato il token o i token di registrazione, puoi iscrivere e annullare l'iscrizione di istanze dell'app client in blocco utilizzando la logica del server.

Puoi iscrivere le istanze dell'app client a qualsiasi argomento esistente oppure crearne uno nuovo. Quando utilizzi l'API per iscrivere un'app client a un nuovo argomento (uno che non esiste già per il tuo progetto Firebase), in FCM viene creato un nuovo argomento con quel nome e qualsiasi client può successivamente iscriversi.

Puoi trasmettere un elenco di token di registrazione al metodo di sottoscrizione Firebase Admin SDK per iscrivere 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);
  });

Java

// 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");

Python

# 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')

Vai

// 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");

Firebase Admin SDK 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);
  });

Java

// 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");

Python

# 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')

Vai

// 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() restituiscono un oggetto contenente la risposta di FCM. Il tipo di restituzione ha lo stesso formato indipendentemente dal numero di token di registrazione specificati nella richiesta.

In caso di errore (autenticazioni non riuscite, token o argomento non validi e così via), questi metodi restituiscono un errore. Per un elenco completo dei codici di errore, incluse descrizioni e procedure di risoluzione, vedi Firebase Admin SDK Errori.

Gestire le iscrizioni agli argomenti dall'app client

Le istanze dell'app client possono anche essere iscritte o annullare l'iscrizione agli argomenti direttamente dalla tua app tramite gli SDK Firebase. Tieni presente che FCM tentativi in caso di errori iniziali per garantire la riuscita dell'abbonamento.

Scegli la tua piattaforma:

Android

Le app client possono iscriversi a qualsiasi argomento esistente o crearne uno nuovo. 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 iscriversi.

Per sottoscrivere un argomento, l'app client chiama Firebase Cloud Messaging subscribeToTopic() con il nome dell'argomento FCM. Questo metodo restituisce un Task, che può essere utilizzato da un listener di completamento per determinare se l'abbonamento è andato a buon fine:

Kotlin

Firebase.messaging.subscribeToTopic("weather")
    .addOnCompleteListener { task ->
        var msg = "Subscribed"
        if (!task.isSuccessful) {
            msg = "Subscribe failed"
        }
        Log.d(TAG, msg)
        Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
    }

Java

FirebaseMessaging.getInstance().subscribeToTopic("weather")
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                String msg = "Subscribed";
                if (!task.isSuccessful()) {
                    msg = "Subscribe failed";
                }
                Log.d(TAG, msg);
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });

Per annullare l'iscrizione, l'app client chiama Firebase Cloud Messaging unsubscribeFromTopic() con il nome dell'argomento.

iOS

Le app client possono iscriversi a qualsiasi argomento esistente o crearne uno nuovo. 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 iscriversi.

Per abbonarti a un argomento, chiama il metodo di abbonamento dal thread principale della tua applicazione (FCM non è thread-safe). Se la richiesta di abbonamento non riesce inizialmente, 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:

Swift

Messaging.messaging().subscribe(toTopic: "weather") { error in
  print("Subscribed to weather topic")
}

Objective-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 il numero unsubscribeFromTopic:topic, e FCM annulla l'iscrizione all'argomento in background.

C++

Per abbonarti a un argomento, chiama ::firebase::messaging::Subscribe dalla tua applicazione. Invia una richiesta asincrona al backend FCM e sottoscrive il client all'argomento specificato.

::firebase::messaging::Subscribe("example");

Se la richiesta di abbonamento non va a buon fine inizialmente, FCM riprova finché non riesce ad abbonarsi all'argomento. Ogni volta che l'app viene avviata, FCM si assicura che tutti gli argomenti richiesti siano stati sottoscritti.

Per annullare l'iscrizione, chiama il numero ::firebase::messaging::Unsubscribe, e FCM annulla l'iscrizione all'argomento in background.

Unity

Per abbonarti a un argomento, chiama Firebase.Messaging.FirebaseMessaging.Subscribe dalla tua applicazione. Invia una richiesta asincrona al backend FCM e sottoscrive il client all'argomento specificato.

Firebase.Messaging.FirebaseMessaging.Subscribe("/topics/example");

Se la richiesta di abbonamento non va a buon fine inizialmente, FCM riprova finché non riesce ad abbonarsi all'argomento. Ogni volta che l'app viene avviata, FCM si assicura che tutti gli argomenti richiesti siano stati sottoscritti.

Per annullare l'iscrizione, chiama Firebase.Messaging.FirebaseMessaging.Unsubscribe, e FCM annulla l'iscrizione all'argomento in background.

Gestione degli argomenti lato server legacy (deprecata)

Per capire cosa sono gli ID istanza, visita la pagina ID istanza. Per informazioni dettagliate sugli endpoint ritirati, consulta i riferimenti API Instance ID.