ios - 向主题发送消息 - Firebase iOS

标签 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];

请帮忙。 谢谢

最佳答案

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

正确的代码如下:

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];

我希望这对以后遇到这个问题的人有所帮助。

关于ios - 向主题发送消息 - Firebase iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46386778/

相关文章:

javascript - 无法进入 JavaScript 中的函数

ios - 顶部/底部布局指南受到限制的奇怪行为

ios - 无法在 UIScrollView 中选择/编辑 UITextView 中的文本

javascript - 当我们使用ref.push写入firebase数据库javascript时会触发哪个事件

objective-c - 向手势识别器初始化选择器发送参数?

iphone - 自动释放池与垃圾回收有什么联系?

postgresql - 是否可以将 firebase 云 firestore 数据导出到 postgresql?

ios - 如何让UIImageView像电影片尾字幕一样滚动?

ios - UIAlertView 不应调用 popViewControllerAnimated

ios - 应用程序不断崩溃,由于未捕获的异常而终止应用程序 'NSInvalidArgumentException'