จัดการการติดตามหัวข้อ

คุณสามารถติดตามแอปไคลเอ็นต์ในหัวข้อจากเซิร์ฟเวอร์หรือไคลเอ็นต์ได้โดยทำดังนี้

  • ในเซิร์ฟเวอร์โดยใช้ 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 ซึ่ง Listener การเสร็จสมบูรณ์ใช้เพื่อพิจารณาว่า การสมัครใช้บริการสำเร็จหรือไม่

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 จะยกเลิกการติดตามหัวข้อในเบื้องหลัง

การจัดการหัวข้อฝั่งเซิร์ฟเวอร์เดิม (เลิกใช้งานแล้ว)

หากต้องการทำความเข้าใจว่ารหัสอินสแตนซ์คืออะไร โปรดไปที่หน้ารหัสอินสแตนซ์ โปรดดูรายละเอียดเกี่ยวกับ ปลายทางที่เลิกใช้งานแล้วที่ ข้อมูลอ้างอิง API ของรหัสอินสแตนซ์