Firebase从设备(IOS)发送推送通知

3

我在iOS中使用Firebase数据库和FCM。我需要通过设备令牌从一个设备向另一个设备发送推送通知。我有FCM API "https://fcm.googleapis.com/fcm/send",这是一个POST方法,并添加参数,例如:

Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data" : {
    ...
  },
}

但是当我尝试调用这个API时,它总是返回一个错误,而从Android设备调用相同的API在Android中工作,而不是在iOS中。以下是我的代码和错误,请给我解决方案。
-(void)sendPush
{



     NSDictionary *noti = @{@"body": @"This is a Firebase Cloud Messaging Topic Message", @"title": @"high"};
    NSDictionary *data = @{@"text": @"This is a Firebase Cloud Messaging Topic Message", @"title": @"high"};
    NSDictionary *params = @{@"to": @"dbpuoXnzY3o:APA91bH3AE_XCbsLpOXycNULcSh1GHzohEFdopmzkY_n8bm78E9_5fHyY3PLCwi5HtTLU_IoOwfdbDc5qCbyzc6tD9Ahg0EviCfbAmhftmMsPqfi0WC...",@"notification":noti,@"data":data};
    NSLog(@"%@",params);

    [NetworkManager postNotification:params getUrl:@"https://fcm.googleapis.com/fcm/send" success:^(id response) {
         NSLog(@"%@",response);



    } failure:^(NSError *error) {

    }];

}

在NSLog中,它看起来像这样

{
    data =     {
        text = "This is a Firebase Cloud Messaging Topic Message";
        title = high;
    };
    notification =     {
        body = "This is a Firebase Cloud Messaging Topic Message";
        title = high;
    };
    to = "dbpuoXnzY3o:APA91bH3AE_XCbsLpOXycNULcSh1GHzohEFdopmzkY_n8bm78E9_5fHyY3PLCwi5HtTLU_IoOwfdbDc5qCbyzc6tD9Ahg0EviCfbAmhftmMsPqfi0WC...";
}

Afnetworking调用函数

 AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];


    manager.responseSerializer = [AFJSONResponseSerializer
                                  serializerWithReadingOptions:NSJSONReadingAllowFragments];
   // [manager.requestSerializer setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"AIzaSyADxgFPrxx....." forHTTPHeaderField:@"key"];

   // NSLog(@"Token==%@",[GeneralSetting sharedInstance].token_number);
    [manager POST:URL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:appDelegate.window animated:YES];
        success(responseObject);

        ////NSLog(@"success!");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
        [MBProgressHUD hideHUDForView:appDelegate.window animated:YES];
      NSLog(@"error: %@", error.description);

        // [self alert:@"" title:@""];
    }];

错误是

error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)" UserInfo={NSUnderlyingError=0x17024a1d0 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x17402fa40> { URL: https://fcm.googleapis.com/fcm/send } { status code: 401, headers {
    "Cache-Control" = "private, max-age=0";
    "Content-Encoding" = gzip;
    "Content-Length" = 259;
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Tue, 04 Jul 2017 10:17:43 GMT";
    Expires = "Tue, 04 Jul 2017 10:17:43 GMT";
    Server = GSE;
    "alt-svc" = "quic=\":443\"; ma=2592000; v=\"39,38,37,36,35\"";
    "x-content-type-options" = nosniff;
    "x-frame-options" = SAMEORIGIN;
    "x-xss-protection" = "1; mode=block";
} },

请帮我,给我解决方案。

我已经尝试使用Postman,它可以工作。

enter image description here

我正在尝试从代码中发送相同的数据,但不起作用,可能是发送字典的问题。我正在使用以下代码:

NSDictionary *noti = @{@"body": @"Hello", @"title": @"This is test message"};

    NSDictionary *params = @{@"to": [GeneralSetting sharedInstance].token_number,@"notification":noti};
    NSLog(@"%@",params);

并且

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"key=AIzaSy.....tBxdYAIRp2KBG0NoS8dOqgy4" forHTTPHeaderField:@"Authorization"];

响应是

{
    notification =     {
        body = Hello;
        title = "This is test message";
    };
    to = "dQgCDOK3sec:APA91zFbkqkgyTNrsYsEmUJwpCtMs1VAmXF9DpF_zQfBYui3UjCA9nYtS_TK549RPnlWEfe-jSvD9MMc3lTFNsGJlyIOqNm84s8GoW1LfTGG0geuWEclb";
}

 Request failed: bad request (400)

你用Postman测试过了吗?那个API能正常工作吗? - Mathi Arasan
我不知道Postman,我必须尝试从FCM控制台发送推送,然后设备通过设备令牌接收推送。 - Nishant Chandwani
所需的内容类型为 acceptableContentTypes = application/json,请在顶部进行提及。您的错误显示您只设置了内容类型 "Content-Type" = "text/html; charset=UTF-8"; - Mathi Arasan
我已经更新了我的问题,我正在使用Postman并且它可以工作,Postman可以发送推送,但是在代码中进行一些更正后,我收到了错误的请求错误。 - Nishant Chandwani
你有比较过POSTMAN的content-type和响应吗?还要检查其他内容。 - Mathi Arasan
你能上传你的最终代码吗?它已经可以正常运行了吗? - riddhi
2个回答

1
你可以选择以下方式之一:
1) 允许你的应用程序接受 text/html 数据:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
// OR
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

2) 或者更好的方法是,根据@user3589771提到的,更改数据类型为application/json

确保AFHTTPSessionManager正确使用AFJSONRequestSerializer格式化JSON。

参考资料:这里这里


0

只需遵循这个简单的POST方法

使用Objective C进行推送通知

    NSDictionary *noti= @{@
        "body" : @"This is an FCM notification message with device token !",
        @"title" : @"FCM Message",
    };
    NSDictionary *params = @{@"to": @"devicetoken",@"notification":noti};
        NSLog(@"%@",params);

    NSError *error;
    NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:&error];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"POST"];
    [request setURL:[NSURL URLWithString:@"https://fcm.googleapis.com/fcm/send"]];

    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"key=AAAAz_****" forHTTPHeaderField:@"Authorization"];
    [request setHTTPBody: postData];


    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

        if(error != nil) {
            NSLog(@"error is comming %@", error);
        }
        NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
                                                            NSLog(@"The response is: %@", asHTTPResponse);

    }] resume];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接