XCode (iPhone) posting a JSON object to a cakePHP server? - xcode

I've got cakePHP running on my server. I'm trying to have my iPhone App post a JSON object to the server, then have the server echo it back. (Keeping it simple for now.) I've accessed the server plenty with normal URLs and gotten views back including JSON objects. This is my first attempt at posting JSON to the server. But it doesn't work. It always echos a null back.
In my iPhone App
NSDictionary* myDict = [NSDictionary dictionaryWithObjects:dictObjects forKeys:dictKeys];
NSData* jsonObject = [NSJSONSerialization dataWithJSONObject:myDict options:NSJSONWritingPrettyPrinted error:nil];
NSData *requestData;
// I've tried it both ways with this stringified or not
/*
NSString* jsonString = [[NSString alloc]initWithData:jsonObject encoding:NSUTF8StringEncoding];
requestData = [NSData dataWithBytes:jsonString length:[jsonString length]];
*/
requestData = [NSData dataWithData:jsonObject];
urlString = [NSString stringWithFormat:#"http://www.myServer.com/json_tests/echo_json"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:requestData];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setValue:[NSString stringWithFormat:#"%d",[jsonObject length]] forHTTPHeaderField:#"Content-Length"];
currentConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
My CakePHP Server
This is in my controller file
public function echo_json() {
$rawData = $this->params['form'];
$decodedData = json_decode($rawData);
$this->layout = 'json';
$this->set(compact('rawData', 'decodedData'));
}
My view has ... echo $rawData; echo json_encode($decodedData);
But you know raw html source code doesn't get displayed here.

Related

Xcode Webview or HttpRequest not Working, after many times tried

I work on a hybrid based Xcode application, processing requirement app request to many times to server, this is same time WebView content loading, same times HttpRequest with POST, any time after many requests, web will or httpRequest not more working, by HttpRequest return always null and by WebView content not more load (blank screen), for that I become any errors on console or by catch, if I remove app from device and install again, is all work perfectly again.
My HttpRequest:
NSString * stringURLComplete = `http://mydomain.c`
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:stringURLComplete]];
[req setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[req setHTTPBody:[strData dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPMethod:#"POST"];
NSError * err = nil;
NSURLResponse * response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSDictionary *resulta = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *list = [resulta objectForKey:#"data"];
return list;

App terminates when using NSURL with parameters

In my app I sent a request to my PHP file to download some info. Whenever I use the code below it will terminate:
-(void)downloadItems
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:#"commentsId"];
NSLog(#"The comments id is : %#",myString);
// Download the json file
NSString *urlstring = [NSString stringWithFormat:#"http:/MyWebSite.com/checkphp.php?title=%#", myString];
NSURL *jsonFileUrl = [NSURL URLWithString:urlstring];
NSLog(#"The qasida id is: %#", jsonFileUrl);
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}
But if I remove myString from urlString like this:
NSURL *jsonFileUrl = [NSURL URLWithString:#"http:/myWebSite/checkphp.php?title=%#"];
the app will not terminate and it will retrieve data.
Can any one tell me what is wrong with my code?
Thanks

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);
}
}];
}

leaks when using NSData, NSURL,NSMutableURLRequest,NSURLConnection and sendSynchronousRequest

I am getting the leak at this line in below code" NSData *returnData = [NSURLConnection ..........."
NSURL *finalURL = [NSURL URLWithString:curl];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10];
[theRequest setHTTPMethod:#"GET"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
BOOL enabled = [self getAutoGenerateObject:returnData];
return enabled;
please help me out of this problem.
Thank You,
Madan Mohan
You will need to release the returnData. That's why in Apple's examples in 'URL Loading Programming Guide / Using NSURLConnection', the returnData is assigned to an iVar and release in dealloc or connectionDidFinishLoading in the case of Asynchronous communication.
Depending what operation you are performing in you method getAutoGeneratedObject, but in theory it can take ownership there.
You could also mark returnData as autoreleased, but that is not always recommended especially if the response data is large.
NSURL *finalURL = [NSURL URLWithString:curl];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10];
[theRequest setHTTPMethod:#"GET"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
BOOL enabled = [self getAutoGenerateObject:returnData];
[returnData release];
return enabled;

Resources