firebase messaging - topic messaging on iOS

27 篇文章 0 订阅

转载方便查阅。

Topic Messaging on iOS

Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.

For example, users of a local weather forecasting app could opt in to a "severe weather alerts" topic and receive notifications of storms threatening specified areas. Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams.

Some things to keep in mind about topics:

  • Topic messaging supports unlimited topics and subscriptions for each app.
  • Topic messaging is best suited for content such as news, weather, or other publicly available information.
  • Topic messages are optimized for throughput rather than latency. For fast, secure delivery to single devices or small groups of devices, target messages to registration tokens, not topics.
  • If you need to send messages to multiple devices per user, consider device group messaging for those use cases.

Subscribe the client app to a topic

Client apps can subscribe to any existing topic, or they can create a new topic. When a client app subscribes to a new topic name (one that does not already exist for your Firebase project), a new topic of that name is created in FCM and any client can subsequently subscribe to it.

The FIRMessaging class handles topic messaging functionality. To subscribe to a topic, call subscribeToTopic:topic from your application's main thread (FCM is not thread-safe):

 
     
[[ FIRMessaging messaging ] subscribeToTopic :@ "news" ]; NSLog (@ "Subscribed to news topic" );

This makes an asynchronous request to the FCM backend and subscribes the client to the given topic. If the subscription request fails initially, FCM retries until it can subscribe to the topic successfully. Each time the app starts, FCM makes sure that all requested topics have been subscribed.

To unsubscribe, call unsubscribeFromTopic:topic, and FCM unsubscribes from the topic in the background.

Manage topic subscriptions on the server

You can take advantage of Instance ID APIs to perform basic topic management tasks from the server side. Given the registration token(s) of client app instances, you can do the following:

Receive and handle topic messages

FCM delivers topic messages in the same way as other downstream messages.

Implement AppDelegate application:didReceiveRemoteNotification: as shown:

SWIFT
OBJECTIVE-C
 
      
- ( void ) application :( UIApplication *) application didReceiveRemoteNotification :( NSDictionary *) userInfo {
 
// 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 message ID.
 
if ( userInfo [ kGCMMessageIDKey ]) {
   
NSLog (@ "Message ID: %@" , userInfo [ kGCMMessageIDKey ]);
 
}

 
// Print full message.
 
NSLog (@ "%@" , userInfo );
}

- ( 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 message ID.
 
if ( userInfo [ kGCMMessageIDKey ]) {
   
NSLog (@ "Message ID: %@" , userInfo [ kGCMMessageIDKey ]);
 
}

 
// Print full message.
 
NSLog (@ "%@" , userInfo );

  completionHandler
( UIBackgroundFetchResultNewData );
}

Build send requests

Sending messages to a Firebase Cloud Messaging topic is very similar to sending messages to an individual device or to a user group. The app server sets the topic key in the message body with a value like yourTopic. Developers can choose any topic name that matches the regular expression: "[a-zA-Z0-9-_.~%]+".

To send to combinations of multiple topics, the app server sets the condition key to a boolean condition that specifies the target topics. For example, to send messages to devices that subscribed to TopicA and either TopicB or TopicC:

 
     
'TopicA' in topics && ( 'TopicB' in topics || 'TopicC' in topics )

FCM first evaluates any conditions in parentheses, and then evaluates the expression from left to right. In the above expression, a user subscribed to any single topic does not receive the message. Likewise, a user who does not subscribe to TopicA does not receive the message. These combinations do receive it:

  • TopicA and TopicB
  • TopicA and TopicC

You can include up to five topics in your conditional expression, and parentheses are supported. Supported operators: &&||!. Note the usage for !:

 
     
!( 'TopicA' in topics )

With this expression, any app instances that are not subscribed to TopicA, including app instances that are not subscribed to any topic, receive the message.

For more detail about app server keys, see the reference information.

Topic HTTP POST request

Send to a single topic:

 
     
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" ,       }     } }

Send with 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!",
  },
  "topic" : "foo-bar"
}'
"https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1"

Send to devices subscribed to topics "dogs" or "cats":

 
     
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" ,     }   } }

Send with 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"

Topic HTTP response

 
     
{
   
"name" : "projects/myproject-b5ae1/messages/5735743068807585451"
}

For the full list of message options, see the HTTP v1 API reference.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值