管理主題訂閱項目

您可以從伺服器或用戶端,讓用戶端應用程式訂閱主題:

  • 在伺服器上,使用 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 中建立該名稱的新主題,之後任何用戶端都能訂閱。

如要訂閱主題,用戶端應用程式會使用 FCM 主題名稱呼叫 Firebase Cloud Messaging subscribeToTopic()。這個方法會傳回 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:topicFCM 會在背景取消訂閱主題。

C++

如要訂閱主題,請從應用程式呼叫 ::firebase::messaging::Subscribe。這會對 FCM 後端發出非同步要求,並讓用戶端訂閱指定主題。

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

如果訂閱要求一開始失敗,FCM 會重試,直到成功訂閱主題為止。應用程式每次啟動時,FCM 都會確保所有要求的主題都已訂閱。

如要取消訂閱,請呼叫 ::firebase::messaging::UnsubscribeFCM 會在背景取消訂閱主題。

Unity

如要訂閱主題,請從應用程式呼叫 Firebase.Messaging.FirebaseMessaging.Subscribe。這會對 FCM 後端發出非同步要求,並讓用戶端訂閱指定主題。

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

如果訂閱要求一開始失敗,FCM 會重試,直到成功訂閱主題為止。應用程式每次啟動時,FCM 都會確保所有要求的主題都已訂閱。

如要取消訂閱,請呼叫 Firebase.Messaging.FirebaseMessaging.UnsubscribeFCM 會在背景取消訂閱主題。

舊版伺服器端主題管理 (已淘汰)

如要瞭解執行個體 ID,請前往執行個體 ID 頁面。如要瞭解已淘汰的端點,請參閱執行個體 ID API 參考資料