서버 또는 클라이언트에서 클라이언트 앱을 주제에 구독할 수 있습니다.
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);
});
자바
// 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);
});
자바
// 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: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 참조를 참고하세요.