发送消息给主题 - Firebase iOS

时间:2017-09-24 05:07:53

标签: ios objective-c firebase

我想从我的客户端应用程序向使用Firebase订阅特定主题的其他设备发送消息。 Firebase文档告诉我如何发送此请求以部署此消息:

主题HTTP POST请求 发送到一个主题:

https://fcm.googleapis.com/fcm/send  
Content-Type:application/json  
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{  
  "to" : /topics/foo-bar",  
  "priority" : "high",  
  "notification" : {  
    "body" : "This is a Firebase Cloud Messaging Topic Message!",  
    "title" : "FCM Message",  
  }  
}

我不知道如何在我的代码中实现这一点而我尝试但没有成功,这是我的代码:

NSDictionary *dic1 = @{
                       @"body : "  : @"This is a Firebase Cloud Messaging Topic Message",
                       @"title : " : @"FCM Message"
                       };

NSDictionary *dic2 = @{
                      @"to : " : @"/topics/news",
                      @"priority : " : @"high",
                      @"notification : " : dic1

                      };

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://fcm.googleapis.com/fcm/send"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"key=MYKEY" forHTTPHeaderField:@"Authorization"];

NSError *error;
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:dic1 options:NSJSONWritingPrettyPrinted error:&error]];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

请帮忙。 感谢

1 个答案:

答案 0 :(得分:0)

我找到了问题的解决方案。

正确的代码如下:

NSDictionary *dic1 = @{
                       @"body"  : @"This is a Firebase Cloud Messaging Topic Message",
                       @"title" : @"FCM Message"
                       };

NSDictionary *dic2 = @{
                       @"to" : @"/topics/news",
                       @"priority" : @"high",
                       @"notification" : dic1
                       };

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://fcm.googleapis.com/fcm/send"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"key=YOURKEY" forHTTPHeaderField:@"Authorization"];
NSError *error;
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:dic2 options:NSJSONWritingPrettyPrinted error:&error]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request] resume];

我希望这将有助于解决此问题的任何人。