إدارة الاشتراكات في المواضيع

يمكنك الاشتراك في موضوع من تطبيق العميل إما من الخادم أو العميل:

  • على الخادم، باستخدام Firebase Admin SDK

  • على الجهاز، باستخدام واجهة برمجة التطبيقات من جهة العميل داخل تطبيقك

إدارة الاشتراكات في المواضيع باستخدام Admin SDK

تتيح لك السمة Firebase Admin SDK تنفيذ مهام أساسية لإدارة المواضيع من جهة الخادم. وباستخدام رموز التسجيل، يمكنك الاشتراك وإلغاء الاشتراك في مثيلات تطبيق العميل بشكل مجمّع باستخدام منطق الخادم.

يمكنك الاشتراك في مثيلات تطبيق العميل في أي موضوع حالي، أو يمكنك إنشاء موضوع جديد. عند استخدام واجهة برمجة التطبيقات للاشتراك في تطبيق عميل في موضوع جديد (موضوع غير متوفّر حاليًا في مشروعك على Firebase)، يتم إنشاء موضوع جديد بهذا الاسم في خدمة "المراسلة عبر السحابة الإلكترونية من Firebase"، ويمكن لأي عميل الاشتراك فيه بعد ذلك.

يمكنك تمرير قائمة برموز التسجيل إلى طريقة 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، ويمكن أن تستخدمها أداة معالجة الإكمال لتحديد ما إذا كان الاشتراك ناجحًا:

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

إدارة المواضيع القديمة من جهة الخادم (متوقّفة نهائيًا)

للتعرّف على أرقام تعريف المثيل، انتقِل إلى صفحة أرقام تعريف المثيل. للاطّلاع على تفاصيل حول نقاط النهاية المتوقّفة نهائيًا، يُرجى الرجوع إلى مراجع واجهة برمجة التطبيقات Instance ID API.