How to make HTTP Get request objective-c - 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

Related

How to check if NSURLSessionDataTask is complete?

I am getting a n number of json data, and once the whole thing is downloaded or the process of getting the json is complete I need to update the UI of the tableView
for(int i = 1;i <= self.numberOfEpisodes;i++)
{
NSString *endPoint = [[[[urlJson stringByAppendingString:getEpisodes]stringByAppendingString:title]stringByAppendingString:#"&episodeNumber="]stringByAppendingString:[NSString stringWithFormat:#"%i",i]];
endPoint = [endPoint stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSLog(#"End point %#",endPoint);
[downloadJson:endPoint WithHandler:^(__weak id result)
{
NSArray *episodeArray =result;
if(episodeArray && episodeArray.count > 0)
{
for(NSDictionary *dictionary in episodeArray)
{
//parse stuff here
}
}
if(i == self.numberOfEpisodes)
{
//update UI
}
}];
}
The problem is in this line if(i == self.numberOfEpisodes). I don't know why the integer i is not arranged from 1 to the self.numberOfEpisodes. Instead it is a random number from 1 to self.numberOfEpisodes. So is there another way how to check if the getting of the json is complete?
(void)getJson:(NSString *)urlString WithHandler:(void(^)(__weak id result))handler
{
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:urlString];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setHTTPMethod:#"GET"];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
id returnedObject = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error:nil];
handler(returnedObject);
}
else{
NSLog(#"error %#",error);
}
}];
[dataTask resume];
}
Yes there is one way to achieve this by dispatch_group_t
//Creat group
dispatch_group_t group = dispatch_group_create();
for(int i = 1;i <= self.numberOfEpisodes;i++)
{
//Enter group
dispatch_group_enter(group);
NSString *endPoint = [[[[urlJson stringByAppendingString:getEpisodes]stringByAppendingString:title]stringByAppendingString:#"&episodeNumber="]stringByAppendingString:[NSString stringWithFormat:#"%i",i]];
endPoint = [endPoint stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSLog(#"End point %#",endPoint);
[downloadJson:endPoint WithHandler:^(__weak id result)
{
NSArray *episodeArray =result;
if(episodeArray && episodeArray.count > 0)
{
for(NSDictionary *dictionary in episodeArray)
{
//parse stuff here
}
}
// Then Leave group
dispatch_group_leave(group);
}];
}
//Here you will be notified after it's done
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// Do whatever you need to do when all requests are finished
//Update UI
});

uber api ride request getting 401 unautherized error response

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.

NSMutableURLRequest sending 2 times while using NSURLSession

I am using NSMutableURLRequest is working correct when I am using
- (void)postAsynchronousOnQueue:(NSOperationQueue*)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))completionHandler {
NSURLRequest* request = [self createPostRequest];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:completionHandler];
}
-(NSURLRequest*)createPostRequest {
NSMutableURLRequest* request = [[HttpRequest requestWithRelativePath:#"/photo"] toNSMutableURLRequest];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[self encodeParamsForUpload]];
return request;
}
But the issue is when my app is in background mode it won't work.
Here is my HttpRequest class method:
+(id)requestWithRelativePath:(NSString*)docpath {
return [[HttpRequest alloc] initWithRelativePath:docpath server:server username:email password:password];
}
-(id)initWithRelativePath:(NSString*)docpath server:(NSString*)server username:(NSString*)username password:(NSString*)password {
if (self = [super init]) {
docpath = [docpath stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
_request = [self createRequestWithDocPath:docpath server:server username:username password:password];
}
return self;
}
- (NSMutableURLRequest*)createRequestWithDocPath:(NSString*)docpath server:(NSString*)server username:(NSString*)username password:(NSString*)password {
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"https://%#%#", server, docpath]];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setTimeoutInterval:120.0];
if ((username != nil) && (password != nil)){
NSString *authStr = [NSString stringWithFormat:#"%#:%#", username, password];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [self base64Encoding:authData]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
}
return request;
}
From, stack overflow I found NSURLSession to work API calls in background. So I used NSURLSession. Here is my updated code which I did:
- (void)postAsynchronousOnQueue:(NSOperationQueue*)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))completionHandler {
NSURLRequest* request = [self createPostRequest];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:completionHandler];
}
-(NSURLRequest*)createPostRequest {
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration ephemeralSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSMutableURLRequest* request = [[HttpRequest requestWithRelativePath:#"/photo"] toNSMutableURLRequest];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[self encodeParamsForUpload]];
//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
[[NSURLSession sharedSession]invalidateAndCancel];
}];
[dataTask resume];
return request;
}
But, when I am using NSURLSession the request is sending two times I already put the breakpoints in NSMutableURLRequestline but it call only once.
Please, help me to solve the issue.
Your createPostRequest is creating a request and submitting it via NSURLSession. But it also returns the NSURLRequest and postAsynchronousOnQueue proceeds to submit it again, this time through the deprecated NSURLConnection.
Remove the NSURLConnection code and just rely upon NSURLSession to issue the request.
For example:
- (void)postAsynchronousOnQueue:(NSOperationQueue*)queue completionHandler:(void (^)(NSData *, NSURLResponse*, NSError*))completionHandler {
NSURLSession *defaultSession = [NSURLSession sharedSession];
NSMutableURLRequest* request = [[HttpRequest requestWithRelativePath:#"/photo"] toNSMutableURLRequest];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[self encodeParamsForUpload]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
[queue addOperationWithBlock:^{
completionHandler(data, response, error);
}];
}];
[dataTask resume];
}

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?

Soundcloud OAuth request returns always invalid client

Here is my objective-c code to obtain access token from SoundCloud:
- (void) authoriseSoundcloud {
NSString *apiUrl = #"https://api.soundcloud.com/oauth2/token";
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[ NSURL URLWithString:apiUrl]];
NSString * params = [NSString stringWithFormat:#"client_id=%#&client_secret=%#grant_type=password&username=%#&password=%#",client,secretKey,fldUsername.text,fldPassword.text ];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *defaultSession = [NSURLSession sharedSession];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}];
[dataTask resume];
}
However, I always get the result 401- {"error":"invalid_client"}.
However, that client ID works perfectly with those requests, that does not need authorization and I have checked multiple times, that my client ID and secret are correct.
As there is not much samples for iOS to use those parameters in HTTP post body, I assume that maybe my parameters list is incorrect. Any ideas from Soundcloud engineers?
Just a typo mistake, simply add "&" between "client_secret=%#" and "grant_type", like this :
NSString * params = [NSString stringWithFormat:#"client_id=%#&client_secret=%#&grant_type=password&username=%#&password=%#",client,secretKey,fldUsername.text,fldPassword.text ];
Work like a charm :)