Gestire le iscrizioni agli argomenti

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

  • Sul server, utilizzando il Firebase Admin SDK.

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

Gestire gli abbonamenti agli argomenti utilizzando l'SDK Admin

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

Puoi abbonare le istanze dell'app client a qualsiasi argomento esistente o crearne uno nuovo. Quando utilizzi l'API per abbonare 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ò abbonarsi successivamente.

Puoi passare un elenco di token di registrazione al metodo di Firebase Admin SDK abbonamento per abbonare 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");

Anche Firebase Admin SDK ti consente di annullare l'abbonamento 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 restituito ha lo stesso formato indipendentemente dal numero di token di registrazione specificati nella richiesta.

In caso di errore (errori di autenticazione, token o argomento non validi e così via), questi metodi generano un errore. Per un elenco completo dei codici di errore, incluse le descrizioni e i passaggi per la risoluzione, consulta Firebase Admin SDK Errori.

Gestire gli abbonamenti agli argomenti dall'app client

Le istanze dell'app client possono anche essere abbonate o annullate agli argomenti direttamente dall'app tramite gli SDK Firebase. Tieni presente che FCM riprova in caso di errori iniziali per garantire che l'abbonamento vada a buon fine.

Scegli la tua piattaforma:

Android

Le app client possono abbonarsi a qualsiasi argomento esistente o crearne uno nuovo argomento. Quando un'app client si abbona 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ò abbonarsi successivamente.

Per abbonarsi a 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'abbonamento, l'app client chiama Firebase Cloud Messaging unsubscribeFromTopic() con il nome dell'argomento.

iOS

Le app client possono abbonarsi a qualsiasi argomento esistente o crearne uno nuovo argomento. Quando un'app client si abbona 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ò abbonarsi successivamente.

Per abbonarti a un argomento, chiama il metodo di abbonamento dal thread principale dell'applicazione (FCM non è thread-safe). Se la richiesta di abbonamento non va a buon fine inizialmente, FCM riprova automaticamente. Nei casi in cui l'abbonamento non può essere completato, l'abbonamento genera un errore che puoi intercettare in un gestore di completamento come mostrato di seguito:

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 abbona 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 abbonati. Per annullare l'abbonamento, chiama unsubscribeFromTopic:topic, e FCM annulla l'abbonamento all'argomento in background.

C++

Per abbonarti a un argomento, chiama ::firebase::messaging::Subscribe dalla tua applicazione. Questa operazione effettua una richiesta asincrona al FCM backend e abbona 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 abbonati.

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

Unity

Per abbonarti a un argomento, chiama Firebase.Messaging.FirebaseMessaging.Subscribe dalla tua applicazione. Questa operazione effettua una richiesta asincrona al FCM backend e abbona 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 abbonati.

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

Gestione degli argomenti lato server legacy (deprecata)

Per capire cosa sono gli Instance ID, visita la pagina Instance ID. Per informazioni dettagliate su gli endpoint deprecati, consulta i riferimenti alle API Instance ID.