uber api ride request getting 401 unautherized error response - objective-c

I am trying to build mac osx application For UBER.I have completed all steps of Aouth2. I am successfully getting access_token. I am also able to retrieve user profile and history but while I am trying to post "ride request", I am getting 401 unauthorized error response.please help.Thank you In advance.
My code is as below.
**
//POST /v1/requests
NSString *sandBoxURL=#"https://sandbox-api.uber.com/v1";
NSString *url = [NSString stringWithFormat:#"%#/requests", sandBoxURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request addValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:[NSString stringWithFormat:#"Bearer %#", _accessToken] forHTTPHeaderField:#"Authorization"];
NSError *error = nil;
request.HTTPMethod = #"POST";
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSLog(#"Request for Product Request:%#",request);
[self performNetworkOperationWithRequest:request completionHandler:^(NSDictionary *requestDictionary, NSURLResponse *response, NSError *error)
{
NSLog(#"Response for Product Request:%#",response);
NSLog(#"Result:%#",requestDictionary);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300)
{ //OK
UberRequest *requestResult = [[UberRequest alloc] initWithDictionary:requestDictionary];
// handler(requestResult, response, error);
}
if (409 == httpResponse.statusCode) { //needs surge confirmation
NSLog(#"Surge Conflict");
}
else
{
NSLog(#"Error In response");
}
}];
**
And response I am getting is:
{ URL: https://sandbox-api.uber.com/v1/requests } { status code: 401, headers {
Connection = "keep-alive";
"Content-Length" = 83;
"Content-Type" = "application/json";
Date = "Mon, 07 Nov 2016 11:19:35 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=0";
"X-Content-Type-Options" = nosniff;
"X-Uber-App" = "uberex-sandbox, migrator-uberex-sandbox-optimus";
"X-Uber-Missing-Scopes" = true;
"X-XSS-Protection" = "1; mode=block";
} }
Result:{
code = unauthorized;
message = "Requires at least one scope. Available scopes: ";
}

I got the solution. Problem Was With My Scope input.While requesting for token,even if the account you are login is of developer, we need put scopes properly. In my case I needed request scope in token.

Related

How to make HTTP Get request objective-c

I have a host where going my key and hid check.
Host is showing there are no any requests.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://host/key.php?keys=cf7dc026e243bf862d60256099a63e58n2gc49b56d84a2148c130d2c010ff87feb3f&hid=1"]];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Request reply: %#", requestReply);
}] resume];
There is my Key.php, where is going check for key and hid.
All server code written on php.
Server is MySQL. Server encoding is a UTF8
<?php
require 'config.php';
ob_end_clean();
$response = null;
$license = R::findOne('license', ' key_code = ? ', array(
$_GET['keys']
));
if (is_null($license)) $response = set_response(false, 400, "Key doesn’t exist");
else if(intval(strtotime($license->data_okonch))==0 || $license->hid == "nulled") $response = set_response(false, 400, "Key zeroed");
else if (intval(strtotime(date("Y-m-d"))) > intval(strtotime($license->data_okonch)))
$response =set_response(false, 400, "License expired");
{
else if (is_null($license->hid))
$license->hid = $_GET['hid'];
R::store($license);
$response = set_response(true, 200, "Successful. HID was updated");
}
else if (strval($_GET['hid']) == strval($license->hid)) $response = set_response(true, 200, "Successful, HID wasn’t updated");
else if (strval($_GET['hid']) != strval($license->hid)) $response = set_response(false, 400, "HID doesn’t match");
Once I finally sended request, I don’t know how. I don’t changed code and later it again doesn’t work

UBER Ride Reminder Api Responding 403 Forbidden Response

I am working on UBER ride reminders api.i am trying to post ride reminder using my server_token.passing required parameter but in response i am getting 403 forbidden response. my http request is as follows.
NSDictionary *event=#{
#"time":event_time,
#"name":event_name
};
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:reminder.reminder_time forKey:#"reminder_time"];
[params setValue:reminder.phone_number forKey:#"phone_number"];
[params setValue:event forKey:#"event"];
NSString *url=#"https://api.uber.com/v1.2/reminders?server_token=***our server token***";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSError *error=nil;
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSURLResponse *response = nil;
[request addValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSData *authData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(!error && authData!=NULL)
{
NSError *jsonError = nil;
NSDictionary *authDictionary = [NSJSONSerialization JSONObjectWithData:authData options:0 error:&jsonError];
if(!jsonError && authDictionary !=nil)
{
NSLog(#"got respose");
}
else
{
NSLog(#"Error retrieving access token %#", jsonError);
}
}
else
{
NSLog(#"Error in sending request for access token %#", error);
}
and response object I am getting from this is as follows
<NSHTTPURLResponse: 0x600000029100> { URL: https://api.uber.com/v1.2/reminders?server_token=wMV7Y-ssag45YXzyTYZnYD7lCDNiBBKaG6Botcv7 } { status code: 403, headers {
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "application/json";
Date = "Thu, 06 Apr 2017 07:39:50 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=604800";
"Transfer-Encoding" = Identity;
"X-Content-Type-Options" = nosniff;
"X-Uber-App" = "uberex-nonsandbox, optimus, migrator-uberex-optimus";
"X-XSS-Protection" = "1; mode=block";
} }
and json response is this
{
code = forbidden;
message = Forbidden;
}

Internal Error 500 when sending facebook photo urls >720p to server

I am trying to send photo urls which are of more than some 700 px . But when i am sending to the data through API . Some photos are uploading but the other were showing 500 internal error .
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:[#"Bearer " stringByAppendingString:[[NSUserDefaults standardUserDefaults]valueForKey:#"authKey"]] forHTTPHeaderField:#"Authorization"];
NSString *urlString=[API Link =%#",fbPic];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSInteger statusCode = operation.response.statusCode;
}failure:^(AFHTTPRequestOperation *operation, NSError *error)
{ NSLog(#"Error: %#", error);
NSInteger statusCode = operation.response.statusCode;
}
];
and here is the error
status code: 500, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 175;
"Content-Type" = "text/plain; charset=utf-8";
Date = "Wed, 29 Jun 2016 12:04:03 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";}
HTTP 500 error indicate that the error comes from the server. You should check with the server developper to get more details

Objective C - Watson Speech-To-Text API responds with 400 Bad Request error

I'm trying to get text response for my audio files (1 minute long duration).
My Code:
NSDictionary *headers = #{ #"authorization": #"Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXFpUG5YcA==",
#"content-type": #"audio/wav",
#"transfer-encoding": #"chunked" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true&inactivity_timeout=-1"]];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSUInteger responseStatusCode = [httpResponse statusCode];
if(responseStatusCode == 200){
callback(error,data);
} else{
[StaticClass showAlertWithTitle:#"Error" Message:#"Watson returned an error!"];
NSError *err = [NSError errorWithDomain:#"Watson non-fatal issue" code:responseStatusCode userInfo:nil];
[CrashlyticsKit recordError:err];
callback(error,nil);
}
}];
[task resume];
This code gives proper response for more than 50% of the times.
But rest of the times, it gives a 400 Bad Request error:
{
code = 400;
"code_description" = "Bad Request";
error = "unable to transcode data stream audio/wav -> audio/x-float-array ";
}
I'm using .wav files for uploading.
Also, the error shows up only when the duration of file is more than a minute; for files with smaller duration the code works fine.
Can anyone point me in the right direction?

Could not find JSON-RPC

Error when creating playlist with Brightcove's Media API in objective c:
{"method":"update_video","params":{"video":{"id":"myID","economics":"AD_SUPPORTED"},"token":"myToken.."}}
{"name":"MissingJSONError","message":"Could not find JSON-RPC.","code":211}, "result": null, "id": null}
Make sure to send the JSON as form data rather than as the raw post body. This works, but I'm not an objective c expert.
NSString *urlString = #"https://api.brightcove.com/services/post";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"application/x-www-form-urlencoded"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSString *data = #"json={\"method\":\"update_video\",\"params\":{\"video\":{\"id\":\"myID\",\"economics\":\"AD_SUPPORTED\"},\"token\":\"myToken..\"}}";
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"%#",content);
Make sure to send the JSON as "multipart/form-data" rather than as the raw "application/json" post body.
My HTTPClient:
private static async void GetStatus2()
{
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
string refId = "5e6c4d61-554c-42cc-ac34-cf3f3c5ba36d";
string writeToken = "ueBq0azalcY3KhCxNPsiGyv-aH4kOQUxpm5YXX6vsT2DIE9W3d5MPQ..";
var statusRequest = new GetStatusRequest(refId, writeToken);
var statusRequestStr = JsonConvert.SerializeObject(statusRequest);
//Content-Disposition: form-data; name="json"
var stringContent = new StringContent(statusRequestStr);
stringContent.Headers.Add("Content-Disposition", "form-data; name=\"JSONView\"");
//stringContent.Headers.Add("Content-Type", "multipart/form-data;");
content.Add(stringContent, "json");
var message = client.PostAsync("http://api.brightcove.com/services/post", content);
var input = message.Result.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<HTTPGetStatusResponse>(await message.Result.Content.ReadAsStringAsync());
Console.WriteLine(JsonConvert.SerializeObject(response));
Console.Read();
if (response.result == HTTPGetStatusResponse.UploadStatus.ERROR)
{
var ex = string.Format("BrightCove Api Error! Error Code: {0}. Error Name: {1}. Error Message: {2}", response.error.code, response.error.name,
response.error.message);
throw new Exception(ex);
}
}
}
}