クライアント アプリをトピックにサブスクライブするには、サーバーまたはクライアントのいずれかを使用します。
サーバーで Firebase Admin SDK を使用する。
クライアントで、アプリ内のクライアントサイド API を使用する。
Admin SDK を使用してトピック登録を管理する
Firebase Admin SDK を使用して、サーバー側から基本的なトピック管理タスクを行うことができます。クライアント アプリ インスタンスの登録トークンを取得すると、サーバー側のロジックを使用してインスタンスのサブスクライブやサブスクライブ解除を一括で行うことができます。
クライアント アプリのインスタンスは、既存のトピックにサブスクライブすることも、新しいトピックを作成することもできます。API を使用してクライアント アプリを新しいトピック(Firebase プロジェクトにまだ存在していないトピック)にサブスクライブすると、その名前の新しいトピックが FCM に作成され、その後すべてのクライアントがそのトピックにサブスクライブできるようになります。
これらの登録トークンのリストを Firebase Admin SDK サブスクリプション メソッドに渡すことにより、対応するデバイスをトピックに登録できます。
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')
Go
// 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 を使用すると、登録トークンを適切なメソッドに渡すことにより、トピックからデバイスのサブスクライブを解除することもできます。
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')
Go
// 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");
subscribeToTopic()
メソッドと unsubscribeFromTopic()
メソッドにより、FCM からのレスポンスを含むオブジェクトが生成されます。戻り値の型は、リクエストで指定された登録トークンの数に関係なく同じ形式です。
問題(認証の失敗、無効なトークンまたはトピックなど)が起きると、これらのメソッドの結果はエラーになります。エラーコードとその説明、および解決手順を含む完全な一覧については、Firebase Admin SDK エラーをご覧ください。
クライアント アプリからトピック登録を管理する
クライアント アプリ インスタンスは、Firebase SDK を介してアプリからトピックに直接登録または登録解除することもできます。FCM は、最初の失敗時に再試行して、サブスクリプションが成功するようにします。
プラットフォームを選択します。
Android
クライアント アプリは、既存のトピックにサブスクライブすることも、新しいトピックを作成することもできます。クライアント アプリを新しいトピック名(Firebase プロジェクトにまだ存在していないトピック名)にサブスクライブすると、その名前の新しいトピックが FCM に作成され、その後すべてのクライアントがそのトピックにサブスクライブできるようになります。
トピックを登録するには、クライアント アプリが Firebase Cloud Messaging subscribeToTopic()
を呼び出し、トピック名 FCM を指定します。このメソッドは Task
を返します。この戻り値により、完了リスナーはサブスクリプションが正常に完了したかどうかを判断できます。
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(); } });
サブスクライブを解除する場合、クライアント アプリは、トピック名を指定して Firebase Cloud Messaging unsubscribeFromTopic()
を呼び出します。
iOS
クライアント アプリは、既存のトピックにサブスクライブすることも、新しいトピックを作成することもできます。クライアント アプリを新しいトピック名(Firebase プロジェクトにまだ存在していないトピック名)にサブスクライブすると、その名前の新しいトピックが FCM に作成され、その後すべてのクライアントがそのトピックにサブスクライブできるようになります。
トピックにサブスクライブするには、アプリケーションのメインスレッドからサブスクリプション メソッドを呼び出します(FCM はスレッドセーフではありません)。最初のサブスクリプション リクエストが失敗すると、FCM は自動的に再試行します。サブスクリプションを完了できなければ、そのサブスクリプションはエラーをスローします。その場合、次のように完了ハンドラでエラーをキャッチできます。
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"); }];
これにより、FCM バックエンドへの非同期リクエストが作成され、所定のトピックにクライアントがサブスクライブされます。subscribeToTopic:topic
を呼び出す前に、コールバック didReceiveRegistrationToken
を介してクライアント アプリ インスタンスがすでに登録トークンを受信していることを確認してください。
アプリが起動するごとに、FCM は、リクエストされたすべてのトピックにサブスクライブされていることを確認します。サブスクライブを解除するには、unsubscribeFromTopic:topic
を呼び出します。これにより、FCM がバックグラウンドでトピックからのサブスクライブ解除を行います。
C++
トピックにサブスクライブするには、アプリケーションから ::firebase::messaging::Subscribe
を呼び出します。これにより、FCM バックエンドへの非同期リクエストが作成され、所定のトピックにクライアントがサブスクライブされます。
::firebase::messaging::Subscribe("example");
最初のサブスクリプション リクエストが失敗した場合、FCM はトピックに正しくサブスクライブできるまで試行を繰り返します。アプリが起動するごとに、FCM は、リクエストされたすべてのトピックにサブスクライブされていることを確認します。
サブスクライブを解除するには、::firebase::messaging::Unsubscribe
を呼び出します。これにより、FCM がバックグラウンドでトピックからのサブスクライブ解除を行います。
Unity
トピックにサブスクライブするには、アプリケーションから Firebase.Messaging.FirebaseMessaging.Subscribe
を呼び出します。これにより、FCM バックエンドへの非同期リクエストが作成され、所定のトピックにクライアントがサブスクライブされます。
Firebase.Messaging.FirebaseMessaging.Subscribe("/topics/example");
最初のサブスクリプション リクエストが失敗した場合、FCM はトピックに正しくサブスクライブできるまで試行を繰り返します。アプリが起動するごとに、FCM は、リクエストされたすべてのトピックにサブスクライブされていることを確認します。
サブスクライブを解除するには、Firebase.Messaging.FirebaseMessaging.Unsubscribe
を呼び出します。これにより、FCM がバックグラウンドでトピックからのサブスクライブ解除を行います。
以前のサーバーサイドのトピック管理(非推奨)
インスタンス ID について詳しくは、インスタンス ID のページをご覧ください。非推奨のエンドポイントの詳細については、インスタンス ID API リファレンスをご覧ください。