หากต้องการกำหนดเป้าหมายข้อความไปยังอุปกรณ์หลายเครื่อง ให้ใช้การรับส่งข้อความตามหัวข้อ ฟีเจอร์นี้ช่วยให้คุณ ส่งข้อความไปยังอุปกรณ์หลายเครื่องที่เลือกรับหัวข้อใดหัวข้อหนึ่งได้
บทแนะนำนี้มุ่งเน้นที่การส่งข้อความตามหัวข้อจากเซิร์ฟเวอร์แอปโดยใช้ Admin SDK หรือ REST API สำหรับ FCM รวมถึงการรับและจัดการข้อความเหล่านั้น ในแอป Apple หน้านี้แสดงขั้นตอนทั้งหมดในการดำเนินการนี้ ตั้งแต่การตั้งค่าไปจนถึง การยืนยัน ดังนั้นอาจมีขั้นตอนที่คุณทำเสร็จแล้วหากคุณได้ ตั้งค่าแอปไคลเอ็นต์ Apple สำหรับ FCM หรือทำตามขั้นตอนเพื่อส่งข้อความแรก
เพิ่ม Firebase ไปยังโปรเจ็กต์ Apple
ส่วนนี้ครอบคลุมงานที่คุณอาจทำเสร็จแล้วหากเปิดใช้ฟีเจอร์อื่นๆ ของ Firebase สำหรับแอปแล้ว สำหรับ FCM โดยเฉพาะ คุณจะต้องอัปโหลดคีย์การตรวจสอบสิทธิ์ APNs และลงทะเบียนรับการแจ้งเตือนจากระยะไกล
ข้อกำหนดเบื้องต้น
ติดตั้งสิ่งต่อไปนี้
- Xcode 16.2 ขึ้นไป
ตรวจสอบว่าโปรเจ็กต์เป็นไปตามข้อกำหนดต่อไปนี้
- โปรเจ็กต์ต้องกำหนดเป้าหมายเป็นแพลตฟอร์มเวอร์ชันต่อไปนี้หรือเวอร์ชันที่ใหม่กว่า
- iOS 13
- macOS 10.15
- tvOS 13
- watchOS 7
- โปรเจ็กต์ต้องกำหนดเป้าหมายเป็นแพลตฟอร์มเวอร์ชันต่อไปนี้หรือเวอร์ชันที่ใหม่กว่า
ตั้งค่าอุปกรณ์ Apple จริงเพื่อเรียกใช้แอป และทําตามงานต่อไปนี้
- รับคีย์การตรวจสอบสิทธิ์ข้อความ Push ของ Apple สำหรับบัญชีนักพัฒนาแอปของ Apple
- เปิดใช้ข้อความ Push ใน XCode ในส่วนแอป > ความสามารถ
- ลงชื่อเข้าใช้ Firebase ด้วยบัญชี Google
หากยังไม่มีโปรเจ็กต์ Xcode และเพียงต้องการลองใช้ผลิตภัณฑ์ Firebase คุณสามารถดาวน์โหลดตัวอย่างการเริ่มต้นใช้งานอย่างรวดเร็วของเราได้
สร้างโปรเจ็กต์ Firebase
ก่อนที่จะเพิ่ม Firebase ลงในแอป Apple ได้ คุณต้องสร้างโปรเจ็กต์ Firebase เพื่อเชื่อมต่อกับแอปของคุณ ไปที่ทำความเข้าใจโปรเจ็กต์ Firebase เพื่อดูข้อมูลเพิ่มเติมเกี่ยวกับโปรเจ็กต์ Firebase
ลงทะเบียนแอปกับ Firebase
หากต้องการใช้ Firebase ในแอป Apple คุณต้องลงทะเบียนแอปกับโปรเจ็กต์ Firebase การลงทะเบียนแอปมักเรียกว่า "การเพิ่ม" แอปไปยังโปรเจ็กต์
ไปที่คอนโซล Firebase
ที่กึ่งกลางหน้าภาพรวมโปรเจ็กต์ ให้คลิกไอคอน iOS+ เพื่อเปิดเวิร์กโฟลว์การตั้งค่า
หากเพิ่มแอปไปยังโปรเจ็กต์ Firebase แล้ว ให้คลิกเพิ่มแอป เพื่อแสดงตัวเลือกแพลตฟอร์ม
ป้อนรหัสชุดของแอปในช่องรหัสชุด
(ไม่บังคับ) ป้อนข้อมูลแอปอื่นๆ ดังนี้ ชื่อเล่นของแอปและรหัส App Store
คลิกลงทะเบียนแอป
เพิ่มไฟล์การกำหนดค่า Firebase
คลิกดาวน์โหลด GoogleService-Info.plist เพื่อรับ ไฟล์กำหนดค่า Firebase (
GoogleService-Info.plist
) ของแอปย้ายไฟล์การกำหนดค่าไปยังรูทของโปรเจ็กต์ Xcode หากได้รับแจ้ง ให้เลือกเพิ่มไฟล์กำหนดค่าไปยังเป้าหมายทั้งหมด
หากมี Bundle ID หลายรายการในโปรเจ็กต์ คุณต้องเชื่อมโยง Bundle ID แต่ละรายการกับแอปที่ลงทะเบียนไว้ในFirebase Console เพื่อให้แต่ละแอปมีไฟล์ GoogleService-Info.plist
ของตัวเองได้
เพิ่ม Firebase SDK ลงในแอป
ใช้ Swift Package Manager เพื่อติดตั้งและจัดการทรัพยากร Dependency ของ Firebase
- เปิดโปรเจ็กต์แอปใน Xcode แล้วไปที่File > Add Packages
- เมื่อได้รับข้อความแจ้ง ให้เพิ่มที่เก็บ SDK ของแพลตฟอร์ม Apple ของ Firebase ดังนี้
- เลือกFirebase Cloud Messaging คลัง
- เพิ่มแฟล็ก
-ObjC
ลงในส่วนแฟล็ก Linker อื่นๆ ของการตั้งค่าบิลด์ของเป้าหมาย - เพื่อประสบการณ์การใช้งาน Firebase Cloud Messaging ที่ดีที่สุด เราขอแนะนําให้ เปิดใช้ Google Analytics ในโปรเจ็กต์ Firebase และเพิ่ม Firebase SDK สําหรับ Google Analytics ลงในแอป คุณสามารถ เลือกไลบรารีที่ไม่มีการเก็บรวบรวม IDFA หรือที่มีการเก็บรวบรวม IDFA ก็ได้ ดูคำถามที่พบบ่อยเกี่ยวกับ การจัดระเบียบโมดูลล่าสุดใน Google Analytics สำหรับ Firebase SDK
- เมื่อเสร็จแล้ว Xcode จะเริ่มจับคู่ข้อมูลและดาวน์โหลดทรัพยากร Dependency ในเบื้องหลังโดยอัตโนมัติ
https://github.com/firebase/firebase-ios-sdk.git
อัปโหลดคีย์การตรวจสอบสิทธิ์ APNs
อัปโหลดคีย์การตรวจสอบสิทธิ์ APNs ไปยัง Firebase หากยังไม่มีคีย์การตรวจสอบสิทธิ์ APNs โปรดสร้างคีย์ใน Apple Developer Member Center
-
ภายในโปรเจ็กต์ในFirebaseคอนโซล ให้เลือกไอคอน รูปเฟือง เลือก การตั้งค่าโปรเจ็กต์ แล้วเลือกแท็บ Cloud Messaging
-
ในคีย์การตรวจสอบสิทธิ์ APNs ภายในการกำหนดค่าแอป iOS ให้คลิกปุ่มอัปโหลด
-
เรียกดูตำแหน่งที่คุณบันทึกคีย์ เลือกคีย์ แล้วคลิกเปิด เพิ่มรหัสคีย์สำหรับคีย์ (มีอยู่ใน ศูนย์สมาชิกนักพัฒนาซอฟต์แวร์ของ Apple) แล้วคลิก อัปโหลด
เริ่มต้น Firebase ในแอป
คุณจะต้องเพิ่มโค้ดการเริ่มต้น Firebase ลงในแอปพลิเคชัน นำเข้า โมดูล Firebase และกำหนดค่าอินสแตนซ์ที่ใช้ร่วมกันดังที่แสดง
- นำเข้าโมดูล
FirebaseCore
ในUIApplicationDelegate
รวมถึงโมดูล Firebase อื่นๆ ที่ตัวแทนแอปของคุณใช้ เช่น หากต้องการใช้ Cloud Firestore และ Authentication ให้ทำดังนี้SwiftUI
import SwiftUI import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Swift
import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Objective-C
@import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ...
- กำหนดค่า
FirebaseApp
อินสแตนซ์ที่แชร์ใน เมธอดapplication(_:didFinishLaunchingWithOptions:)
ของตัวแทนแอปSwiftUI
// Use Firebase library to configure APIs FirebaseApp.configure()
Swift
// Use Firebase library to configure APIs FirebaseApp.configure()
Objective-C
// Use Firebase library to configure APIs [FIRApp configure];
- หากใช้ SwiftUI คุณต้องสร้างตัวแทนแอปพลิเคชันและแนบไปกับโครงสร้าง
App
ผ่านUIApplicationDelegateAdaptor
หรือNSApplicationDelegateAdaptor
นอกจากนี้ คุณยังต้องปิดใช้การสวิซเซิลการมอบสิทธิ์ของแอปด้วย ดูข้อมูลเพิ่มเติมได้ที่วิธีการสำหรับ SwiftUISwiftUI
@main struct YourApp: App { // register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } }
ลงทะเบียนรับการแจ้งเตือนระยะไกล
ไม่ว่าจะตอนเริ่มต้นหรือที่จุดที่ต้องการในขั้นตอนการสมัคร ให้ ลงทะเบียนแอปสำหรับการแจ้งเตือนจากระยะไกล เรียกใช้registerForRemoteNotifications
ดังที่แสดง
Swift
UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { _, _ in } ) application.registerForRemoteNotifications()
Objective-C
[UNUserNotificationCenter currentNotificationCenter].delegate = self; UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge; [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { // ... }]; [application registerForRemoteNotifications];
สมัครใช้บริการแอปไคลเอ็นต์ไปยังหัวข้อ
แอปไคลเอ็นต์สามารถติดตามหัวข้อที่มีอยู่ หรือสร้างหัวข้อใหม่ได้ เมื่อแอปไคลเอ็นต์สมัครรับข้อมูลชื่อหัวข้อใหม่ (ชื่อที่ยังไม่มีในโปรเจ็กต์ 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 จะยกเลิกการสมัครรับข้อมูลหัวข้อนี้ในเบื้องหลัง
รับและจัดการข้อความของหัวข้อ
FCM จะส่งข้อความตามหัวข้อในลักษณะเดียวกับข้อความดาวน์สตรีมอื่นๆ
ใช้ application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
ดังที่แสดง
Swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async -> UIBackgroundFetchResult { // 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) return UIBackgroundFetchResult.newData }
Objective-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)
Go
// 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)
C#
// 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);
REST
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
คุณใส่หัวข้อในนิพจน์แบบมีเงื่อนไขได้สูงสุด 5 หัวข้อ
หากต้องการส่งไปยังเงื่อนไข ให้ทำดังนี้
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)
Go
// 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)
C#
// 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);
REST
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
ขั้นตอนถัดไป
- คุณใช้เซิร์ฟเวอร์เพื่อสมัครรับข้อมูลอินสแตนซ์แอปไคลเอ็นต์ในหัวข้อและ ทำงานด้านการจัดการอื่นๆ ได้ ดูจัดการการติดตามหัวข้อในเซิร์ฟเวอร์