簡體   English   中英

Firebase從設備(IOS)發送推送通知

[英]Firebase send push notification from devices (IOS)

在ios中我使用的是Firebase數據庫和FCM。 我必須通過設備令牌從設備向設備發送推送通知。 我有FCM API“ https://fcm.googleapis.com/fcm/send ”這是post方法並添加參數Like:

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...";
}

遠程工作調用功能

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

請幫幫我,請給我解決方案

我從郵遞員那里嘗試過,這是從郵遞員那里開始的

在此輸入圖像描述

我從代碼發送的相同數據不起作用可能是問題是發送字典我正在使用此代碼

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)

你可以:

1)允許您的應用接受text/html數據:

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
// OR
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

2)或者更好,更改您的數據類型,因為它是application/json@ user3589771所述。

確保AFHTTPSessionManager被正確地格式化JSON AFJSONRequestSerializer

參考文獻: 這里這里

按照這個 - 簡單的post方法

使用目標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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM