Cannot do HTTP PUT action in NSURLConnection - ios

Hi I am trying to Http PUT method in NSURLConnection.
I am posting data file to an amazon s3 path.
-(void)postFaceVideo{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://face_video.s3.amazonaws.com/chunks/?AWSAccessKeyId=MYKEY&Expires=1424373411&Signature=MYSIGNATURE"]];
[request setHTTPMethod:#"PUT"];
[request setHTTPBody:appDelegate.faceData]; // This is the saved NSData
[request setTimeoutInterval:200];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
webData = [NSMutableData data];
}
}
Before it was working fine, but now neither data is posted in the server nor any response is coming. What could be the reason?
Is there any change in these method in Xcode 6, because previously it worked fine when I was working with Xcode 5.
Also I have tried with NSURLSession as follows.
-(void)postFaceVideo2{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://face_video.s3.amazonaws.com/chunks/?AWSAccessKeyId=MYKEY&Expires=1424373411&Signature=MYSIGNATURE"]];
[request setValue:[NSString stringWithFormat:#"%d",appDelegate.faceData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"PUT";
request.HTTPBody = appDelegate.faceData;
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response, NSError *error)
{
if (!error)
{
NSLog(#"Status code: %i", ((NSHTTPURLResponse *)response).statusCode);
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
}
else
{
NSLog(#"Error: %#", error.localizedDescription);
NSLog(#"Error: %#", error.description);
}
}];
[task resume];
}
Here I am getting the error as -
Error: Error Domain=NSURLErrorDomain Code=-1001 "The operation couldn’t be completed. (NSURLErrorDomain error -1001.)" UserInfo=0x171cadb0 {NSErrorFailingURLKey=https://video_test.s3.amazonaws.com/chunks_dev/21662/facescan_1?Signature= MYSIGN =&Expires=1424381789&AWSAccessKeyId=MYID, NSErrorFailingURLStringKey=https://video_test.s3.amazonaws.com/chunks_dev/21662/facescan_1?Signature=MYSIGN=&Expires=1424381789&AWSAccessKeyId=MYID, NSUnderlyingError=0x171b30c0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1001.)"}

Related

Xcode https call to Restful API

I am having an issue in making a call to our RESTful API. The request is to get the token from the API; I need that token to use it to make further calls on that API.
The issue is that whenever I make that call, I get HTTP 403 status code and I don't know why. I am making the same calls from Android but they work fine without any issue.
Actually I have no experience at all to work with xCode; I am just implementing some changes in the existing code which was written by some other developer. I don't know if I am doing something wrong or what.
id keys[] = {#"grant_type", #"client_id", #"client_secret", #"username", #"password"};
id objects[] = {#"password", #"AppClientID", #"AppClientSecret", #"usernamehere", #"userpasswordhere"};
NSUInteger count = sizeof(objects) / sizeof(id);
NSDictionary *d = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"https://oauth-test.websitename.com/token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"Basic" forHTTPHeaderField:#"Authorization"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError) {
if(data.length > 0 && connectionError == nil) {
NSLog(#"Response --> %# ", response);
}
}
];
Can someone try to help me figure out what is actually going wrong?
Thanks in advance.
I ran your code and the log, i am getting is
Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified
hostname could not be found." UserInfo=
{NSUnderlyingError=0x608000059aa0 {Error Domain=kCFErrorDomainCFNetwork
Code=-1003 "A server with the specified hostname could not be found."
UserInfo={NSErrorFailingURLStringKey=http://oauth-
test.websitename.com/token, NSErrorFailingURLKey=http://oauth-
test.websitename.com/token, _kCFStreamErrorCodeKey=8,
_kCFStreamErrorDomainKey=12, NSLocalizedDescription=A server with the
specified hostname could not be found.}},
NSErrorFailingURLStringKey=http://oauth-test.websitename.com/token,
NSErrorFailingURLKey=http://oauth-test.websitename.com/token,
_kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8,
NSLocalizedDescription=A server with the specified hostname could not
be found.}
I tried it with NSUrlSession also but it is giving same problem.
I think your server is not configured
Below is the code with URL session
id keys[] = {#"grant_type", #"client_id", #"client_secret",
#"username", #"password"}; id objects[] = {#"password", #"AppClientID", #"AppClientSecret", #"usernamehere", #"userpasswordhere"};
NSUInteger count = sizeof(objects) / sizeof(id); NSDictionary *d = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"http://oauth-test.websitename.com/token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"Basic" forHTTPHeaderField:#"Authorization"]; [request setHTTPBody:jsonData];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDownloadTask *dataTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(#"%#", response);
}];
[dataTask resume];

Request is blank when sending data through iOS to google cloud endpoint

i am working on Google cloud endpoint with datastore. When i am passing data through Android & iOS with method POST , it is getting saved in datastore with empty record. i.e. request is properly working but the way i am sending data is wrong. please help me for this.
For iOS, code is mentioned below :
NSDictionary *headers = #{ #"content-type": #"application/json",
#"cache-control": #"no-cache",
#"postman-token": #"404012ff-722e-c5d8-48db-fa7fb3260841"};
NSLog(#"header %#",headers);
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"enter url here..."]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSString* strRequest=#"";
strRequest =[[NSString alloc] initWithFormat:#"displayEmail=%#&displayName=%#",#"sonal#gmail.com",#"sonal"];
NSLog(#"url is %# parameter = %#", request , strRequest);
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [strRequest dataUsingEncoding:NSUTF8StringEncoding]];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *responseBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"responce Body===>%#",responseBody);
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"responce%#", httpResponse);
}
}];
[dataTask resume];
You need to set the httpBody property of your request. If you don't provide a body for the POST, of course it's blank.
https://developer.apple.com/reference/foundation/nsmutableurlrequest/1409064-httpbody
Or Objective-C
https://developer.apple.com/reference/foundation/nsmutableurlrequest/1409064-httpbody?language=objc
We got a solution..
we changed the way of passing data..
here is code :
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:syncURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
NSData *requestData = [NSData dataWithBytes:[serverSyncAPIRequestJSON UTF8String] length:[serverSyncAPIRequestJSON length]];[request setHTTPMethod:#"POST"]; [request setHTTPBody:requestData]; [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];

POSTING DATA TO A WS

I'm trying to post new data to a ws but im geting error each time
I need to
1-pass a username and password each time
2-code the data with AES256 WITH THE API KEY
Code:
- (IBAction)AddTicket:(id)sender {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *URL = [[NSURL alloc] initWithString:#"http://dev.enano-tech.com/api/Ticket"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"id",#"1",#"idProject",#"1",#"idTicketType",#"nameo",#"name",#"nameo",#"description", #"1",#"idStatus",#"2016-06-23 15:20:49",#"creationDateTime", nil];
NSData *dataToPost = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSData *final =[dataToPost AES256EncryptWithKey:#"02b6e206868660a0d59d2e51a11fdcd6"];
//
NSLog(#"postData1e == %#",final);
NSLog(#"final %#",dataToPost);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request addValue:#"CURLAUTH_BASIC" forHTTPHeaderField:#"CURLOPT_HTTPAUTH"];
[request addValue:#"Basic YWRtaW46YWRtaW5hZG1pbg==" forHTTPHeaderField:#"authorization"];
[request addValue:#"admin:adminadmin" forHTTPHeaderField:#"CURLOPT_USERPWD"];
[request addValue:#"true" forHTTPHeaderField:#"CURLOPT_RETURNTRANSFER"];
[request addValue:#"false" forHTTPHeaderField:#"CURLOPT_SSL_VERIFYPEER"];
[request addValue:#"POST" forHTTPHeaderField:#"CURLOPT_CUSTOMREQUES"];
[request addValue:#"true" forHTTPHeaderField:#"CURLOPT_POST"];
[request addValue:#"false" forHTTPHeaderField:#"CURLOPT_POSTFIELDS"];
[request setHTTPBody:final];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *str = [[NSString alloc]initWithData:final encoding:NSUTF8StringEncoding];
NSLog(#"data %#",data);
NSLog(#"respoce %#",response);
NSLog(#"result == %#",result);
}];
[postDataTask resume];
}
Response:
2016-08-02 15:06:47.768 Projector[3936:1619429] result == {"error":"invalid API query", "message":"'data' is not correctly encoded for method POST. Request for correct API KEY"}
this is the documentation of api:
enter image description here
Your webserver is missing "data" from the website. To fix it, you'll need to add that field to your form or find the correct field name (case sensitive)

How to check if there is no server response in Objective c

I am trying to hit a web service . All works good. But if the server is not working then my app crashes .
How to handle NO SERVER RESPONSE .
Please help
Here is my code for hitting web service.
NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:#"0" forKey:#"unit"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"req=%#",jsonInputString];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",getCommunity]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData != nil) {
NSDictionary *jsonRecieveDict = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"jsonArray =======%#",jsonRecieveDict);
}
if (error)
{
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Servor not responding" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[errorAlert show];
}
** ERROR IS BECAUSE OF INVALID STATUS CODE FROM SERVER **
if (error != nil) {
// Something went wrong...
NSLog(#"Servor not responding %#",error.description);
return;
}
if ([response statusCode] >= 300) {
NSLog(#"Servor not responding, status code: %ld", (long)[response statusCode]);
return;
}
First condition should be error checking,Second if response comes check the status code then only perform the remaining operation
Also change NSURLResponse *response; to NSHTTPURLResponse *response
OR diff Implementation
NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:#"0" forKey:#"unit"];
if([NSJSONSerialization isValidJSONObject:get]){
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"your url"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session=[NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(response){
NSString *resp = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
NSLog(#"Echo %#",resp);
}
else{
NSLog(#"Timeout");
}
}];
[task resume];
}

Post Method in IPhone programming for logining in to the application

I am trying to Post the email and password in my iPhone application but I don't know why it says connection successful with out entering any data in to the text fields. Code below:
- (IBAction)enterButtonAction:(id)sender
{
NSString *post =[NSString stringWithFormat:#"user[email]=%#&user[password]=%#",[userNameTF text],[passWordTF text]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:#"http://secure.sample.in/login"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connection Successfull");
} else {
NSLog(#"Connection UnSuccessfull");
}
}
You have to actually run this connection. Right now you're just checking if connection pointer is not nil.
But it would be better just to use newest NSURLSession API.
So, something like this:
- (IBAction)enterButtonAction:(id)sender
{
NSURLRequest *request = [self setupRequestWithData:...];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// handle response
}];
[dataTask resume];
}
You could validate the username/password before executing the request.
- (IBAction)enterButtonAction:(id)sender {
if ([[userNameTF text] length] && [[passWordTF text] length]) {
// Execute the request
} else {
// Missing username/password, show an UIAlertView?
}
}
This:
if (connection) {
NSLog(#"Connection Successfull");
} else {
NSLog(#"Connection UnSuccessfull");
}
is equivalent to
if (connection!=nil) {
NSLog(#"Connection Successfull");
} else {
NSLog(#"Connection UnSuccessfull");
}
Since connection isn't nil, the if condition is satisfied.

Resources