NSURLConnection send null data to server - nsurlconnection

I send a registration message to the server like this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
[request setValue:API_KEY forHTTPHeaderField:#"api_key"];
NSString *dataString = [NSString stringWithFormat:#"username=%#&password=%#", username, encryptedPassword];
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
// Connection
NSURLResponse *response = nil;
NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Print results
NSLog(#"response: %#", response);
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"response: %d", [(NSHTTPURLResponse *)response statusCode]);
}
id jsonObject = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&jsonError];
NSLog(#"jsonObject: %#", jsonObject);
The connection was success, but I got the error response:
=> response: 400
=> jsonObject: {
error = "Please provide username.USERNAME:";
}
The server received a null user name, but I'm sure I pass a valid user name to http body (converted into NSData). The data contains the following info (converted back into string):
username=cc24#cc.com&password=12345678nW7wMNio0bsNBHGqY7VgSw%3D%3D
I don't what happened. But the API works fine with Android app.

Related

Storing JSON response in iOS error

I am making a call to an online php from my iOS app. In my output window I see the JSON Response with the data. But I need to store the NSString in my userdefaults but it is coming up NULL.
In this code the NSLog(#"JSON Response is %#", responseData); returns the json data just fine and I see the ipixid. But in the NSLog (#"ipixid is %#", ilixid); it returns ipixid is (null)
NSString *post =[[NSString alloc] initWithFormat:#"email=%#", strValue];
NSLog(#"PostData: %#",post);
NSURL *url1=[NSURL URLWithString:#"http://www.ipixsocial.com/membership/getresult.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url1];
[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];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"JSON Response is %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
// NSString *username = [(NSString *) [jsonData objectForKey:#"email"]init];
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"uid"] integerValue];
NSString* ipixid = [jsonData objectForKey:#"ipixid"];
[[NSUserDefaults standardUserDefaults] setObject:ipixid forKey:#"ipixid"];
NSLog (#"ipixid is %#", ipixid);
Don't ignore the "error" parameter you're passing to the parser. Also check that "jsonData" is not nil. I'm think that parsing is failing and because you're ignoring it and assuming jsonData is valid you're getting nil for [jsonData objectForKey:#"ipixid"];

NSUrlSession iso NSUrlConnection - uploading device token to a MySQL Database

I'm trying to update my code from NSUrlConnection to NSUrlSession. The app is running fine, no errors, but the token is never uploaded to the MySQL database... I've really no idea? Should I implement delegates or am I doing something basic stuff very wrong here? :-)
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"deviceToken"];
//Information is only uploaded to SQLite database if 'deviceToken' is not null
if ([deviceToken length] > 0) {
NSURL *url = [NSURL URLWithString:#"http://sampleUrl.com/do.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *varString = [NSString stringWithFormat:#"deviceToken=%#", deviceToken];
NSData *requestData = [varString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
/*NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:requestData completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
//Handle
}];*/
//NSURLSessionUploadTask *uploadTask2 = [session uploadTaskWithStreamedRequest:request];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
//Handle
}];
[dataTask resume];
Any ideas?
Thanks and regards,
Tom
I solved the problem:
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"deviceToken"];
//Information is only uploaded to SQLite database if 'deviceToken' is not null
if ([deviceToken length] > 0) {
// Create URL and URLRequest
NSURL *url = [NSURL URLWithString:#"http://url.com/something.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//Create the body
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *varString = [NSString stringWithFormat:#"deviceToken=%#", deviceToken"]];
// Create POST parameters and add it to HTTPBody
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [varString dataUsingEncoding:NSUTF8StringEncoding]];
// Set up a simple and asynchronous NSURLSession to send data to the php
// Set up the session configuration and header data
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setRequestCachePolicy:NSURLRequestUseProtocolCachePolicy];
[config setHTTPAdditionalHeaders:#{
#"Accept" : #"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
#"Content-Type" : #"application/x-www-form-urlencoded",
#"Content-Length" : [NSString stringWithFormat:#"%lu", (unsigned long)[[varString dataUsingEncoding:NSUTF8StringEncoding] length]]
}];
// Create the session and the task
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
if (error)
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
if (response)
{
NSLog(#"response description: %#", response.description);
[prefs setBool:YES forKey:#"tokenSent"];
}
if (data)
NSLog(#"data description: %#", data.description);
}];
// Start the task
[task resume];
}
Regards,
Tom

Unsupported URL on ios 8

I'm trying to fetch a json from google places with the following code:
NSString *query = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%i&types=%#&sensor=true&key=%#", center.latitude, center.longitude, rad, types, kGOOGLE_API_KEY];
NSLog(#"%#",query);
NSURL *googleRequestURL=[NSURL URLWithString:query];
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:googleRequestURL] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Error fetching data: %#",[error description]);
} else {
//To-do
}
}];
The resulting url is: https://maps.googleapis.com/maps/api/place/search/json?location=37.337566,-122.041202&radius=1000&types=accounting|bowling_alley|doctor&sensor=true&key=MY_KEY
(my key is ommitted for obsious reasons)
Which works fine from my laptop's browser, but return the error:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0x7fe47bc138f0 {NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7fe47be9dbe0 "unsupported URL"}
I tried using http instead of https (in the browser it returns a json with some error message, but still returns something) with no success.
What am I doing wrong?
This is how I got it resolved. Good Luck!
NSString *google = #"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=500&types=%#&key=%#";
NSString *link = [NSString stringWithFormat:google, coordinate.latitude, coordinate.longitude, types, GOOGLE_KEY];
NSURL *url = [NSURL URLWithString:[link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];

NSMutableURLRequest posting a JSON object to CakePHP appears as an Array

I send JSON data from Xcode in the following way:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"Test title", #"title",
#"Test option1", #"option1",
#"Test option2", #"option2", nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *url = [NSURL URLWithString:#"http://somedomain.com/posts/add"];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
[NSURLConnection connectionWithRequest:request delegate:self];
I write the received data in CakePHP to a file in the following way:
public function add()
{
if ($this->request->is('post'))
if ($this->RequestHandler->requestedWith('json')) {
file_put_contents('debug.txt', print_r($this->request->data, true));
}
}
}
and the data in the file ('debug.txt') looks like this:
Array
(
[option2] => Test option2
[title] => Test title
[option1] => Test option1
)
I know that the data being sent is in JSON format and I expect the received data to appear as JSON format rather than an Array in 'debug.txt'. Is this a correct assumption and if so what is going wrong?
I'm not sure what the problem is here, before you can do anything with that data in PHP you'd have to convert it to an array anyway, it seems the CakePHP requesthandler is doing this automatically for you.
If you really want the original json just json_encode() it back again.

send parameter values and retrieve an xml file Xcode

In my current xcode project, I need to send parameter values to a url and need to retrieve an xml file based on the parameter values sent.
I tried the below code but it's not working:
(IBAction)myButtonClick:(id)sender
{
NSURL *oRequestURL =
[NSURL URLWithString:#"http://xyz .com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-06-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc"];
NSMutableURLRequest *oRequest = [[[NSMutableURLRequest alloc]init]autorelease];
[oRequest setHTTPMethod:#"POST"];
[oRequest setURL: oRequestURL];
NSMutableData *oHttpBody = [NSMutableData data];
[oHttpBody appendData:[#"This is HTTP Request body" dataUsingEncoding:NSUTF8StringEncoding]];
[oRequest setValue:[oHttpBody length] forHTTPHeaderField:#"Content-Length"];
NSError *oError = [[NSError alloc]init];
NSHTTPURLResponse *oResponseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:oRequest returningResponse:oResponseCode error:oError];
if ([oResponseCode statusCode]> 200) {
NSLog(#"Status code is greater than 200");
}
NSString *strResult=[[NSString alloc]initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(#"The result is %s",strResult);
}
I have searched many sites and books but could not find a solution.
Would be of great help if a link to a tutorial or some other useful resource can be provided. Appreciate your great help.
Thank You.
Hi,
I have found the solution. The code is as below. Hope it helps someone else:)
- (IBAction)myButtonPressed:(id)sender
{
NSString *urlAsString = #"http://api.abc.com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-09-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"2193141de2g7e2a34bb19bc3aa52b3b5" forHTTPHeaderField:#"X-XX-API-KEY"];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection
sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length]>0 &&
error == nil)
{
NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
}
else if ([data length]== 0 && error==nil) {
NSLog(#"Nothing was downloaded");
}
else if (error!= nil) {
NSLog(#"Error occured = %#", error);
}
}];
}

Resources