Apple प्लेटफ़ॉर्म पर विषयों पर संदेश भेजें

प्रकाशित/सदस्यता मॉडल के आधार पर, एफसीएम विषय मैसेजिंग आपको कई डिवाइसों पर एक संदेश भेजने की अनुमति देता है जिन्होंने किसी विशेष विषय को चुना है। आप आवश्यकतानुसार विषय संदेश लिखते हैं, और एफसीएम संदेश को सही उपकरणों तक विश्वसनीय रूप से रूट करने और वितरित करने का काम संभालता है।

उदाहरण के लिए, स्थानीय ज्वार पूर्वानुमान ऐप के उपयोगकर्ता "ज्वारीय धाराओं के अलर्ट" विषय को चुन सकते हैं और निर्दिष्ट क्षेत्रों में इष्टतम खारे पानी में मछली पकड़ने की स्थिति की सूचनाएं प्राप्त कर सकते हैं। स्पोर्ट्स ऐप के उपयोगकर्ता अपनी पसंदीदा टीमों के लिए लाइव गेम स्कोर में स्वचालित अपडेट की सदस्यता ले सकते हैं।

विषयों के बारे में ध्यान रखने योग्य कुछ बातें:

  • मौसम, या अन्य सार्वजनिक रूप से उपलब्ध जानकारी जैसी सामग्री के लिए विषय संदेश सबसे उपयुक्त है।
  • विषय संदेशों को विलंबता के बजाय थ्रूपुट के लिए अनुकूलित किया गया है। एकल डिवाइस या डिवाइस के छोटे समूहों में तेज़, सुरक्षित डिलीवरी के लिए, संदेशों को पंजीकरण टोकन पर लक्षित करें , न कि विषयों पर।
  • यदि आपको प्रति उपयोगकर्ता एकाधिक डिवाइस पर संदेश भेजने की आवश्यकता है, तो उन उपयोग के मामलों के लिए डिवाइस समूह मैसेजिंग पर विचार करें।
  • विषय संदेश प्रत्येक विषय के लिए असीमित सदस्यता का समर्थन करता है। हालाँकि, FCM इन क्षेत्रों में सीमाएँ लागू करता है:
    • एक ऐप इंस्टेंस को 2000 से अधिक विषयों के लिए सब्सक्राइब नहीं किया जा सकता है।
    • यदि आप ऐप इंस्टेंस की सदस्यता के लिए बैच आयात का उपयोग कर रहे हैं, तो प्रत्येक अनुरोध 1000 ऐप इंस्टेंस तक सीमित है।
    • नई सदस्यताओं की आवृत्ति प्रति प्रोजेक्ट दर-सीमित है। यदि आप कम समय में बहुत अधिक सदस्यता अनुरोध भेजते हैं, तो FCM सर्वर 429 RESOURCE_EXHAUSTED ("कोटा पार हो गया") प्रतिक्रिया के साथ प्रतिक्रिया देंगे। घातीय बैकऑफ़ के साथ पुनः प्रयास करें।

किसी विषय के लिए क्लाइंट ऐप की सदस्यता लें

क्लाइंट ऐप्स किसी भी मौजूदा विषय की सदस्यता ले सकते हैं, या वे एक नया विषय बना सकते हैं। जब कोई क्लाइंट ऐप किसी नए विषय नाम (जो आपके फायरबेस प्रोजेक्ट के लिए पहले से मौजूद नहीं है) की सदस्यता लेता है, तो उस नाम का एक नया विषय एफसीएम में बनाया जाता है और कोई भी ग्राहक बाद में इसकी सदस्यता ले सकता है।

किसी विषय की सदस्यता लेने के लिए, अपने एप्लिकेशन के मुख्य थ्रेड से सदस्यता विधि को कॉल करें (एफसीएम थ्रेड-सुरक्षित नहीं है)। यदि सदस्यता अनुरोध प्रारंभ में विफल हो जाता है, तो FCM स्वचालित रूप से पुनः प्रयास करता है। ऐसे मामलों के लिए जहां सदस्यता पूरी नहीं की जा सकती, सदस्यता एक त्रुटि फेंकती है जिसे आप पूर्णता हैंडलर में पकड़ सकते हैं जैसा कि दिखाया गया है:

तीव्र

Messaging.messaging().subscribe(toTopic: "weather") { error in
  print("Subscribed to weather topic")
}

उद्देश्य सी

[[FIRMessaging messaging] subscribeToTopic:@"weather"
                                completion:^(NSError * _Nullable error) {
  NSLog(@"Subscribed to weather topic");
}];

यह कॉल एफसीएम बैकएंड के लिए एक अतुल्यकालिक अनुरोध करता है और क्लाइंट को दिए गए विषय की सदस्यता देता है। subscribeToTopic:topic पर कॉल करने से पहले, सुनिश्चित करें कि क्लाइंट ऐप इंस्टेंस को कॉलबैक didReceiveRegistrationToken के माध्यम से पहले ही एक पंजीकरण टोकन प्राप्त हो चुका है।

हर बार ऐप शुरू होने पर, एफसीएम यह सुनिश्चित करता है कि सभी अनुरोधित विषयों की सदस्यता ले ली गई है। सदस्यता समाप्त करने के लिए, unsubscribeFromTopic:topic पर कॉल करें, और FCM पृष्ठभूमि में विषय से सदस्यता समाप्त कर देता है।

सर्वर पर विषय सदस्यताएँ प्रबंधित करें

फायरबेस एडमिन एसडीके आपको सर्वर साइड से बुनियादी विषय प्रबंधन कार्य करने की अनुमति देता है। उनके पंजीकरण टोकन को देखते हुए, आप सर्वर लॉजिक का उपयोग करके थोक में क्लाइंट ऐप इंस्टेंस को सब्सक्राइब और अनसब्सक्राइब कर सकते हैं।

आप किसी भी मौजूदा विषय के लिए क्लाइंट ऐप इंस्टेंस की सदस्यता ले सकते हैं, या आप एक नया विषय बना सकते हैं। जब आप किसी क्लाइंट ऐप को किसी नए विषय (जो आपके फायरबेस प्रोजेक्ट के लिए पहले से मौजूद नहीं है) की सदस्यता लेने के लिए एपीआई का उपयोग करते हैं, तो उस नाम का एक नया विषय एफसीएम में बनाया जाता है और कोई भी क्लाइंट बाद में इसकी सदस्यता ले सकता है।

आप किसी विषय पर संबंधित डिवाइस की सदस्यता लेने के लिए फायरबेस एडमिन एसडीके सदस्यता विधि में पंजीकरण टोकन की एक सूची पास कर सकते हैं:

नोड.जे.एस

// 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");

अजगर

# 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");

एडमिन एफसीएम एपीआई आपको पंजीकरण टोकन को उचित विधि से पास करके किसी विषय से डिवाइस की सदस्यता समाप्त करने की भी अनुमति देता है:

नोड.जे.एस

// 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");

अजगर

# 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 की प्रतिक्रिया होती है। अनुरोध में निर्दिष्ट पंजीकरण टोकन की संख्या की परवाह किए बिना रिटर्न प्रकार का प्रारूप समान है।

किसी त्रुटि (प्रमाणीकरण विफलता, अमान्य टोकन या विषय आदि) के मामले में इन विधियों के परिणामस्वरूप त्रुटि होती है। विवरण और समाधान चरणों सहित त्रुटि कोड की पूरी सूची के लिए, एडमिन एफसीएम एपीआई त्रुटियाँ देखें।

विषय संदेश प्राप्त करें और संभालें

एफसीएम अन्य डाउनस्ट्रीम संदेशों की तरह ही विषय संदेश वितरित करता है।

application(_:didReceiveRemoteNotification:fetchCompletionHandler:) जैसा कि दिखाया गया है:

तीव्र

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
}

उद्देश्य सी

- (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);
}

भेजें अनुरोध बनाएं

आपके द्वारा एक विषय बनाने के बाद, या तो क्लाइंट साइड पर विषय के लिए क्लाइंट ऐप इंस्टेंस की सदस्यता लेकर या सर्वर एपीआई के माध्यम से, आप विषय पर संदेश भेज सकते हैं। यदि आप पहली बार एफसीएम के लिए अनुरोध भेज रहे हैं, तो महत्वपूर्ण पृष्ठभूमि और सेटअप जानकारी के लिए अपने सर्वर वातावरण और एफसीएम के लिए मार्गदर्शिका देखें।

बैकएंड पर अपने भेजने वाले तर्क में, वांछित विषय का नाम निर्दिष्ट करें जैसा कि दिखाया गया है:

नोड.जे.एस

// 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);
  });

जावा

// 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);

अजगर

# 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 -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)"

एफसीएम पहले कोष्ठक में किसी भी स्थिति का मूल्यांकन करता है, और फिर बाएं से दाएं अभिव्यक्ति का मूल्यांकन करता है। उपरोक्त अभिव्यक्ति में, किसी एक विषय की सदस्यता लेने वाले उपयोगकर्ता को संदेश प्राप्त नहीं होता है। इसी तरह, जो उपयोगकर्ता TopicA की सदस्यता नहीं लेता है उसे संदेश प्राप्त नहीं होता है। ये संयोजन इसे प्राप्त करते हैं:

  • TopicA और TopicB
  • TopicA और TopicC

आप अपनी सशर्त अभिव्यक्ति में अधिकतम पाँच विषय शामिल कर सकते हैं।

किसी शर्त पर भेजने के लिए:

नोड.जे.एस

// 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);
  });

जावा

// 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);

अजगर

# 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 -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

अगले कदम