ตามรูปแบบการเผยแพร่/สมัครรับข่าวสาร การส่งข้อความตามหัวข้อ FCM ช่วยให้คุณสามารถส่งข้อความไปยังอุปกรณ์หลายเครื่องที่เลือกใช้หัวข้อเฉพาะ คุณเขียนข้อความหัวข้อตามความจำเป็น และ FCM จะจัดการการกำหนดเส้นทางและส่งข้อความไปยังอุปกรณ์ที่เหมาะสมได้อย่างน่าเชื่อถือ
ตัวอย่างเช่น ผู้ใช้แอปพยากรณ์น้ำในพื้นที่สามารถเลือกหัวข้อ "การแจ้งเตือนกระแสน้ำขึ้นน้ำลง" และรับการแจ้งเตือนเกี่ยวกับสภาพการตกปลาน้ำเค็มที่เหมาะสมที่สุดในพื้นที่ที่กำหนด ผู้ใช้แอปกีฬาสามารถสมัครรับการอัปเดตอัตโนมัติในคะแนนเกมสดสำหรับทีมโปรดของพวกเขา
สิ่งที่ควรทราบเกี่ยวกับหัวข้อ:
- ข้อความหัวข้อเหมาะที่สุดสำหรับเนื้อหา เช่น สภาพอากาศ หรือข้อมูลอื่นๆ ที่เปิดเผยต่อสาธารณะ
- ข้อความหัวข้อได้รับ การปรับให้เหมาะสมสำหรับปริมาณงานมากกว่าเวลาในการตอบสนอง เพื่อการส่งที่รวดเร็วและปลอดภัยไปยังอุปกรณ์เครื่องเดียวหรือกลุ่มอุปกรณ์ขนาดเล็ก ให้ กำหนดเป้าหมายข้อความไปยังโทเค็นการลงทะเบียน ไม่ใช่หัวข้อ
- หากคุณต้องการส่งข้อความไปยังอุปกรณ์หลายเครื่อง ต่อผู้ใช้หนึ่งราย ให้พิจารณา การส่งข้อความกลุ่มอุปกรณ์ สำหรับกรณีการใช้งานเหล่านั้น
- การส่งข้อความตามหัวข้อรองรับการสมัครรับข้อมูลแบบไม่จำกัดสำหรับแต่ละหัวข้อ อย่างไรก็ตาม FCM บังคับใช้ข้อจำกัดในพื้นที่เหล่านี้:
- อินสแตนซ์แอปหนึ่งรายการสามารถสมัครรับข้อมูลได้ไม่เกิน 2,000 หัวข้อ
- หากคุณกำลังใช้ การนำเข้าแบบกลุ่ม เพื่อสมัครใช้งานอินสแตนซ์ของแอป คำขอแต่ละรายการจะถูกจำกัดที่ 1,000 อินสแตนซ์ของแอป
- ความถี่ของการสมัครรับข้อมูลใหม่ถูกจำกัดอัตราต่อโครงการ หากคุณส่งคำขอสมัครรับข้อมูลมากเกินไปในระยะเวลาอันสั้น เซิร์ฟเวอร์ FCM จะตอบสนองด้วยการตอบกลับ
429 RESOURCE_EXHAUSTED
("เกินโควต้า") ลองอีกครั้งด้วยการถอยกลับแบบเอ็กซ์โปเนนเชียล
สมัครสมาชิกแอพไคลเอนต์ในหัวข้อ
แอปไคลเอนต์สามารถสมัครรับหัวข้อที่มีอยู่หรือสร้างหัวข้อใหม่ได้ เมื่อแอปไคลเอ็นต์สมัครรับชื่อหัวข้อใหม่ (ชื่อที่ไม่มีอยู่ในโปรเจ็กต์ Firebase ของคุณ) หัวข้อใหม่ของชื่อนั้นจะถูกสร้างขึ้นใน FCM และไคลเอ็นต์ใดๆ ก็สามารถสมัครรับข้อมูลได้ในภายหลัง
หากต้องการสมัครรับหัวข้อ ให้เรียกวิธีการสมัครรับข้อมูลจากเธรดหลักของแอปพลิเคชันของคุณ (FCM ไม่ปลอดภัยสำหรับเธรด) หากคำขอสมัครสมาชิกล้มเหลวในตอนแรก FCM จะลองใหม่โดยอัตโนมัติ สำหรับกรณีที่ไม่สามารถสมัครสมาชิกให้เสร็จสมบูรณ์ได้ การสมัครสมาชิกจะแสดงข้อผิดพลาดที่คุณสามารถตรวจพบในตัวจัดการความสมบูรณ์ดังที่แสดง:
Swift
Messaging.messaging().subscribe(toTopic: "weather") { error in print("Subscribed to weather topic") }
วัตถุประสงค์-C
[[FIRMessaging messaging] subscribeToTopic:@"weather" completion:^(NSError * _Nullable error) { NSLog(@"Subscribed to weather topic"); }];
การเรียกนี้ทำการร้องขอแบบอะซิงโครนัสไปยังแบ็กเอนด์ FCM และสมัครรับข้อมูลไคลเอ็นต์ในหัวข้อที่กำหนด ก่อนเรียก subscribeToTopic:topic
ตรวจสอบให้แน่ใจว่าอินสแตนซ์ของแอปไคลเอ็นต์ได้รับโทเค็นการลงทะเบียนผ่านการเรียกกลับ didReceiveRegistrationToken
แล้ว
ทุกครั้งที่เปิดแอป FCM จะตรวจสอบให้แน่ใจว่าได้สมัครรับหัวข้อที่ร้องขอทั้งหมดแล้ว หากต้องการยกเลิกการสมัคร ให้โทรไปที่ unsubscribeFromTopic:topic
และ FCM ยกเลิกการสมัครจากหัวข้อในเบื้องหลัง
จัดการการสมัครสมาชิกหัวข้อบนเซิร์ฟเวอร์
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')
ไป
// 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")
ค#
// 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");
Admin FCM API ยังให้คุณยกเลิกการสมัครอุปกรณ์จากหัวข้อโดยส่งโทเค็นการลงทะเบียนไปยังวิธีการที่เหมาะสม:
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')
ไป
// 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")
ค#
// 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 ประเภทการส่งคืนมีรูปแบบเดียวกันโดยไม่คำนึงถึงจำนวนของโทเค็นการลงทะเบียนที่ระบุในคำขอ
ในกรณีที่เกิดข้อผิดพลาด (การตรวจสอบล้มเหลว โทเค็นหรือหัวข้อไม่ถูกต้อง ฯลฯ) วิธีการเหล่านี้ส่งผลให้เกิดข้อผิดพลาด สำหรับรายการรหัสข้อผิดพลาดทั้งหมด รวมถึงคำอธิบายและขั้นตอนการแก้ปัญหา โปรดดูที่ ข้อผิดพลาด Admin FCM API
รับและจัดการข้อความหัวข้อ
FCM ส่งข้อความหัวข้อในลักษณะเดียวกับข้อความปลายทางอื่นๆ
ใช้ application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
ดังที่แสดง:
Swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: \(messageID)") } // Print full message. print(userInfo) completionHandler(UIBackgroundFetchResult.newData) }
วัตถุประสงค์-C
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // With swizzling disabled you must let Messaging know about the message, for Analytics // [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; // ... // Print full message. NSLog(@"%@", userInfo); completionHandler(UIBackgroundFetchResultNewData); }
สร้างคำขอส่ง
หลังจากที่คุณสร้างหัวข้อแล้ว ไม่ว่าจะสมัครใช้งานอินสแตนซ์แอปไคลเอ็นต์ในหัวข้อที่ฝั่งไคลเอ็นต์หรือผ่าน API ของเซิร์ฟเวอร์ คุณจะส่งข้อความไปยังหัวข้อได้ หากนี่เป็นครั้งแรกที่คุณสร้างส่งคำขอสำหรับ FCM โปรดดูคำแนะนำเกี่ยวกับ สภาพแวดล้อมเซิร์ฟเวอร์ของคุณและ FCM สำหรับข้อมูลเบื้องหลังและการตั้งค่าที่สำคัญ
ในตรรกะการส่งของคุณบนแบ็กเอนด์ ให้ระบุชื่อหัวข้อที่ต้องการดังที่แสดง:
Node.js
// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';
const message = {
data: {
score: '850',
time: '2:45'
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Java
// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setTopic(topic)
.build();
// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
Python
# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'
# See documentation on defining a message payload.
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
topic=topic,
)
# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
ไป
// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Topic: topic,
}
// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
ค#
// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";
// See documentation on defining a message payload.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
Topic = topic,
};
// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
พักผ่อน
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"topic" : "foo-bar",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message"
}
}
}
คำสั่ง cURL:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message": {
"topic" : "foo-bar",
"notification": {
"body": "This is a Firebase Cloud Messaging Topic Message!",
"title": "FCM Message"
}
}
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
ในการส่งข้อความไปยังหัวข้อต่างๆ รวมกัน ให้ระบุ เงื่อนไข ซึ่งเป็นนิพจน์บูลีนที่ระบุหัวข้อเป้าหมาย ตัวอย่างเช่น เงื่อนไขต่อไปนี้จะส่งข้อความไปยังอุปกรณ์ที่สมัครใช้ TopicA
และ TopicB
หรือ TopicC
:
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM จะประเมินเงื่อนไขใดๆ ในวงเล็บก่อน จากนั้นจึงประเมินนิพจน์จากซ้ายไปขวา ในนิพจน์ข้างต้น ผู้ใช้ที่สมัครรับข่าวสารในหัวข้อเดียวจะไม่ได้รับข้อความ ในทำนองเดียวกัน ผู้ใช้ที่ไม่ได้สมัครใช้ TopicA
จะไม่ได้รับข้อความ ชุดค่าผสมเหล่านี้ได้รับ:
-
TopicA
และTopicB
-
TopicA
และTopicC
คุณสามารถรวมหัวข้อได้ถึงห้าหัวข้อในนิพจน์เงื่อนไขของคุณ
ในการส่งไปยังเงื่อนไข:
Node.js
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';
// See documentation on defining a message payload.
const message = {
notification: {
title: '$FooCorp up 1.43% on the day',
body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
},
condition: condition
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Java
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
Message message = Message.builder()
.setNotification(Notification.builder()
.setTitle("$GOOG up 1.43% on the day")
.setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
.build())
.setCondition(condition)
.build();
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
Python
# Define a condition which will send to devices which are subscribed
# to either the Google stock or the tech industry topics.
condition = "'stock-GOOG' in topics || 'industry-tech' in topics"
# See documentation on defining a message payload.
message = messaging.Message(
notification=messaging.Notification(
title='$GOOG up 1.43% on the day',
body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
),
condition=condition,
)
# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
ไป
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
condition := "'stock-GOOG' in topics || 'industry-tech' in topics"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Condition: condition,
}
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
ค#
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
var message = new Message()
{
Notification = new Notification()
{
Title = "$GOOG up 1.43% on the day",
Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
},
Condition = condition,
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
พักผ่อน
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"condition": "'dogs' in topics || 'cats' in topics",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message",
}
}
}
คำสั่ง cURL:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"notification": {
"title": "FCM Message",
"body": "This is a Firebase Cloud Messaging Topic Message!",
},
"condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
ขั้นตอนถัดไป
- เรียนรู้เพิ่มเติมเกี่ยวกับวิธีอื่นในการส่งไปยังอุปกรณ์หลายเครื่อง — การส่งข้อความกลุ่มอุปกรณ์