How to post json data to server [duplicate] - iphone

This question already has an answer here:
How to send json post values to a remote server and get the results with iOS 5?
(1 answer)
Closed 9 years ago.
In my iPhone app I want to send my data in JSON format.I have stored all the data in an dictionary.How to change dictionary data in JSON format and then send it to the serve using post method (I need to send to server only).

If your using SBJSON then using the code below you can create JSON string from NSDictionary.
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects:values forKeys:keys];
NSString *jsonString = [jsonWriter stringWithObject:dict];

try it
NSMutableDictionary *Dict=[[NSMutableDictionary alloc] initWithObjectsAndKeys:str,#"str",str1,#"str1",Idstr,#"Idstr",nil];
NSError *error=nil;
NSData *Data=[NSJSONSerialization dataWithJSONObject:Dict options:NSJSONWritingPrettyPrinted error:&error];
NSMutableString *JsonString = [[NSMutableString alloc] initWithData:Data encoding:NSUTF8StringEncoding];
NSMutableString *urlstr=#"url"
NSURL *url=[NSURL URLWithString:urlstr];
NSMutableURLRequest *urlrequest=[NSMutableURLRequest requestWithURL:url];
NSString *urlbody=[NSString stringWithFormat:#"inputParam=%#",JsonString];
[urlrequest setHTTPBody:[Alerturlbody dataUsingEncoding:NSUTF8StringEncoding]];
[urlrequest setHTTPMethod:#"POST"];
[urlrequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Accept"];
[urlrequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlrequest setValue:[NSString stringWithFormat:#"%d", [urlbody length]] forHTTPHeaderField:#"Content-Length"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlrequest queue:queue completionHandler:^(NSURLResponse *response, NSData *Resdata, NSError *error)
{
NSError* error;
NSDictionary *jsondict = [NSJSONSerialization
JSONObjectWithData:Resdata //1
options:kNilOptions
error:&error];
//NSLog(#"jsondict:%#",jsondict);
}
else if ([Resdata length] == 0 && error == nil)
{
NSLog(#"Nothing was downloaded.");
else if (error != nil)
{
NSLog(#"Error happened = %#", error);
}
}];

Related

URL Decoding of json in ios

I am having 1 webservice in php which is having browser url mentioned bel :
http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01 01:00:00
Now when I try to fetch url in my iphone app, it is taking this url:
http://Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00
This is creating problem.
i have used this code for fetching data from my url.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"";
NSString *str;
str = #"LastUpdated";
NSString *requestString = [NSString stringWithFormat:#"{\"LastUpdated\":\"%#\"}",str];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
//urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ACTEC"
message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
......
}
here,i am getting null response as url is getting decoded...How can I make this solved...
Help me out.
Thanks in advance.
NSString *urlLoc = [[fileContents objectForKey:#"URL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postData = [NSMutableData data];
NSMutableURLRequest *urlRequest;
[postData appendData: [[NSString stringWithFormat: #"add your data which you want to send"] dataUsingEncoding: NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:urlLoc]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSString *temp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"\n\nurl =%# \n posted data =>%#",urlLoc, temp);
check nslog. that which data u send to service.
NSData *response = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"json_string >> %#",json_string);
Maybe this will help you.
hey dear just for an another example i just post my this code..
first Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
    [NSURL URLWithString:#"http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00"]];
Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request
    returningResponse:nil error:nil];
Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc]
    initWithData:response encoding:NSUTF8StringEncoding];
Parse the JSON response into an object Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil]
And in statuses array you have all the data you need.
i hope this help you...
:)

Create a JsonString in iOS

I am new in iOS. I created a JSON NSDictionary like this:
NSArray *keys = [NSArray arrayWithObjects:#"User", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"Ali", #"2020", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
And then I could convert it to NSString via two mechanisms:
1)
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
NSString *jsonString = nil;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
2)
NSString *jsonString = [jsonDictionary JSONRepresentation];
In the second way I get this warning :
Instance method '-JSONRepresentation' not found (return type defaults to 'id')
But when I run the project, both of the mechanisms works fine:
NSLog(#"Val of json parse obj is %#",jsonString);
Do you know how can I remove the warning in the second way?
My main goal is POST this json String to an external database using RESTful Web Service.
Basically which way is better considering my main goal?
You should use NSJSONSerialization as it is faster and comes directly with iOS SDK as long as your "target audience" is iOS5+
To POST the data to your web service you need the create a request along these lines...
NSDictionary * postDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"value1", #"value2", nil]
forKeys:[NSArray arrayWithObjects:#"key1", #"key2", nil]];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONReadingMutableContainers error:&error];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"your_webservice_post_url"]];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:jsonData];
NSURLConnection * myConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
Please read up on NSURLConnectionDelegate protocol.
For iOS 5.0 > :
Use NSJSONSerialization like this :
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%# Error:%#", resultAsString,error);
For < iOS 5 :
Use json-framework a third party library that uses category for NSDictionary to provide json string :
NSString *jsonString = [dictionary JSONRepresentation];
//with options
NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil]
This will help you... Convert NSDictionary to JSON with SBJson
use this way i hope it will help you
NSArray *keys = [NSArray arrayWithObjects:#"User", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"Ali", #"2020", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error = nil;
// NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"\n\n\n id for json==%# \n\n\n\n\n",result);
JSON DEFAULT METHOD......
+(NSDictionary *)stringWithUrl:(NSURL *)url postData:(NSData *)postData httpMethod:(NSString *)method {
NSDictionary *returnResponse=[[NSDictionary alloc]init];
#try {
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:180]; [urlRequest setHTTPMethod:method];
if(postData != nil)
{
[urlRequest setHTTPBody:postData];
}
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"text/html" forHTTPHeaderField:#"Accept"];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
returnResponse = [NSJSONSerialization
JSONObjectWithData:urlData
options:kNilOptions
error:&error];
} #catch (NSException *exception) { returnResponse=nil; } #finally { return returnResponse; } }
Return Method :
+(NSDictionary )methodName:(NSString)string {
NSDictionary *returnResponse; NSData *postData = [NSData dataWithBytes:[string UTF8String] length:[string length]]; NSString *urlString = #"https//:..url...."; returnResponse=[self stringWithUrl:[NSURL URLWithString:urlString] postData:postData httpMethod:#"POST"];
return returnResponse;
}

How can I parse JSON object in iPhone SDK?

I need to parse the data I receive the following way:
[
{
"IdEmpleado":1,
"Nombre":"Cesar",
"Edad":"25",
"Genero":"M",
"IdArea":1
},
{
"IdEmpleado":2,
"Nombre":"Luis",
"Edad":"30",
"Genero":"M",
"IdArea":2
}
]
I need to get the data for each employee, in the example are 2 employees need all the fields of each object and then turn them into employees.
I already use the JSON and transfer to an NSDICTIONARY, but how I can do to have it structured so each field and being able to pass a Method to convert an object EMPLOYEE?
http://stig.github.com/json-framework/
You can use the JSONFramework, which you can find here.
https://github.com/stig/json-framework/
NSString *userid= [[NSUserDefaults standardUserDefaults]objectForKey:#"Userid"];
NSString *appurl =[NSString stringWithFormat:#"your link"];
appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSMutableDictionary *deletdict=[returnString JSONValue];
if([[deletdict objectForKey:#"success"] isEqualToString:#"False"])
{
NSLog(#"Unsuccess...");
}
else
{
NSLog(#"success...");
}
AND Post method is this
NSString *post =[NSString stringWithFormat:#"AgencyId=STM&UserId=1&Type=1&Date=%#&Time=%#&Coords=%#&Image=h32979`7~U#)01123737373773&SeverityLevel=2",strDateLocal,strDateTime,dict];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://174.94.153.48:7778/TransitApi/IncidentConfirm/"]]];
[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 *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSMutableArray *SubLiveArray=[str JSONValue];
download Json framework on this link:::
http://mobile.tutsplus.com/tutorials/iphone/iphone-json-twitter-api
NSString *appurl=[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=23.041230,72.514346&radius=50000&types=%#&sensor=true&key=AIzaSyAQZ16VzshxGbYdiM8C2RhhwGl3QwVJTB4",_txt_search.text];

json PUT request

Hi iam usng JSONKit. i need to update status in linkedin site by sending the status update through json request to server. this is the code im sendin. im gettin 400 eroor. please tel me whats the mistake.
thanks.
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"linkedin-html",#"contentType",#"My Fancy Update",#"body",nil];
NSString *str =[jsonDict JSONString];
NSMutableData *requestData = [NSMutableData dataWithBytes:[str UTF8String] length:[str length]];
[self setHTTPBody:requestData];
[self setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[self setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
dont know if this will fit your usage needs exactly, I am using iphone and connecting to jayrock .net webservices.
Here is the command I use to handle all my calls.
Also, I am using the json-framework
- (NSDictionary*) sendJSONRPCRequestTo:(NSString*) url
forCommand:(NSString*)command
withParamaters:(NSMutableArray*) parameters
synchronous:(BOOL) sendSynchronous
{
if (parameters != nil)
{
[parameters setValue:[HSAppData appVersion] forKey:#"AppVersion"];
[parameters setValue:[NSNumber numberWithDouble:[HSAppData currentLocation].longitude] forKey:#"Longitude"];
[parameters setValue:[NSNumber numberWithDouble:[HSAppData currentLocation].latitude] forKey:#"Latitude"];
}
if (self.commandId == nil)
{
self.commandId = #"1";
}
NSMutableURLRequest *request = [self.baseTransaction makeNewRequestFor:url];
NSMutableDictionary *mainPackage = [NSMutableDictionary dictionary];
[mainPackage setValue:self.commandId forKey:#"id"];
[mainPackage setValue:command forKey:#"method"];
[mainPackage setValue:parameters forKey:#"params"];
NSString *jsonData = [mainPackage JSONRepresentation];
[request setValue:command forHTTPHeaderField:#"X-JSON-RPC"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
if (jsonData != nil && [jsonData isEqual:#""] == NO)
{
[request setHTTPMethod:#"POST"];
[request setValue:[[NSNumber numberWithInt:[jsonData length]] stringValue] forHTTPHeaderField:#"Content-Length"];
}
[request setHTTPBody:[jsonData dataUsingEncoding:NSUTF8StringEncoding]];
if (sendSynchronous)
{
NSHTTPURLResponse * response = nil;
NSError * error = nil;
//self.baseTransaction.lastConnection = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *jsonResult = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSDictionary *jsonDict = nil;
#try {
jsonDict = [jsonResult JSONValue];
}
#catch (NSException * e) {
NSLog(#"Error: %#",jsonResult);
jsonDict = [NSMutableDictionary dictionary];
[jsonDict setValue:self.commandId forKey:#"id"];
[jsonDict setValue:#"Unable to call function on server" forKey:#"error"];
[jsonDict setValue:[NSNull null] forKey:#"result"];
}
#finally {
return jsonDict;
}
}
// TODO: Add ASynchronous
// else
// {
// }
}
I would start by writing your json payload and the connection response data to a simple text file and review (or post, if you want us to take a look). I've found that's the easiest way for me to spot issues when posting data to services. You're using a library, so my guess is the payload should be fine, but you never know. The response data may include more hints to the true issue, although I can't say I've ever used LinkedIn's api.
Also, I didn't see where you specified that the request was a "PUT". Did you include
[req setHTTPMethod:#"PUT"];
Use this code to write the payload to the file system (sorry for the formatting, it's not playing nicely with mobile safari):
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *documentPath = [NSString stringWithFormat:#"%#/payloadData.txt", documentsDirectoryPath];
[requestData writeToFile:documentPath atomically:YES];
May be this can help you.

How to send json data in the Http request using NSURLRequest

I'm new to objective-c and I'm starting to put a great deal of effort into request/response as of recent. I have a working example that can call a url (via http GET) and parse the json returned.
The working example of this is below
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
//do something with the json that comes back ... (the fun part)
}
- (void)viewDidLoad
{
[self searchForStuff:#"iPhone"];
}
-(void)searchForStuff:(NSString *)text
{
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.whatever.com/json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
My first question is - will this approach scale up? Or is this not async (meaning I block the UI thread while the app is waiting for the response)
My second question is - how might I modify the request part of this to do a POST instead of GET? Is it simply to modify the HttpMethod like so?
[request setHTTPMethod:#"POST"];
And finally - how do I add a set of json data to this post as a simple string (for example)
{
"magic":{
"real":true
},
"options":{
"happy":true,
"joy":true,
"joy2":true
},
"key":"123"
}
Thank you in advance
Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:#"question"];
This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made.
I struggled with this for a while. Running PHP on the server. This code will post a json and get the json reply from the server
NSURL *url = [NSURL URLWithString:#"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:#"POST"];
NSString *post = [NSString stringWithFormat:#"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil){
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"Server Response (we want to see a 200 return code) %#",response);
NSLog(#"dictionary %#",dictionary);
}
else if ([data length] == 0 && error == nil){
NSLog(#"no data returned");
//no data, but tried
}
else if (error != nil)
{
NSLog(#"there was a download error");
//couldn't download
}
}];
I would suggest to use ASIHTTPRequest
ASIHTTPRequest is an easy to use
wrapper around the CFNetwork API that
makes some of the more tedious aspects
of communicating with web servers
easier. It is written in Objective-C
and works in both Mac OS X and iPhone
applications.
It is suitable performing basic HTTP
requests and interacting with
REST-based services (GET / POST / PUT
/ DELETE). The included
ASIFormDataRequest subclass makes it
easy to submit POST data and files
using multipart/form-data.
Please note, that the original author discontinued with this project. See the followring post for reasons and alternatives: http://allseeing-i.com/%5Brequest_release%5D;
Personally I am a big fan of AFNetworking
Most of you already know this by now, but I am posting this, just incase, some of you are still struggling with JSON in iOS6+.
In iOS6 and later, we have the NSJSONSerialization Class that is fast and has no dependency on including "outside" libraries.
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
This is the way iOS6 and later can now parse JSON efficiently.The use of SBJson is also pre-ARC implementation and brings with it those issues too if you are working in an ARC environment.
I hope this helps!
Here is a great article using Restkit
It explains on serializing nested data into JSON and attaching the data to a HTTP POST request.
Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as
This edit was intended to address the author of the post and makes no
sense as an edit. It should have been written as a comment or an
answer
I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation dependency with NSJSONSerialization as Rob's comment with 15 upvotes suggests.
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:#"question"];
Here's an updated example that is using NSURLConnection +sendAsynchronousRequest: (10.7+, iOS 5+), The "Post" request remains the same as with the accepted answer and is omitted here for the sake of clarity:
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:#"http://www.myserver.com/api/api.php?request=%#", #"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(#"%#", responseString);
}
}
}];
You can try this code for send json string
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:#"www.test.com?xyz.php&param=%#",jsonString];