iOS 5 http query with JSON object - ios

On iOS 5, how can I query a web service using a JSON object?
I've tried a bunch of different approaches and can't get it to work. It appears that the AFNetworking or RestKit frameworks are the easiest routes, but I don't have experience with either. I'm also new to iOS development.
Here's an example query that works:
https://site.com/gis?QUERY={"ARGUMENTS":{"TO":{"OBJECT_TYPE":"BUILDING","OBJECT_ID":"1","TYPE":"IDENTIFIER"},"FROM":{"OBJECT_TYPE":"BUILDING","OBJECT_ID":"2","TYPE":"IDENTIFIER"},"PATHTYPES":["SIDEWALK"},"QUERYTYPE":"FINDPATH"}

Create a url request, see example below. This posts json data. In your case, your using a GET http method, so you shouldn't need to post the json data, you can simply include it in the url. Note that some of my variable declarations are not shown.
NSArray *keys = [NSArray arrayWithObjects:#"longitude", #"latitude", nil];
NSArray *objects = [NSArray arrayWithObjects:longitude, latitude, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
__jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
__jsonString = [[NSString alloc]initWithData:__jsonData encoding:NSUTF8StringEncoding];
}
// Be sure to properly escape your url string.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:#"https://site.com...etc"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: __jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [__jsonData length]] forHTTPHeaderField:#"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
// Handle error.
}
else
{
NSError *jsonParsingError = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
}

Related

I want to pass the array inside the dictionary parameter with URL POST method

I am new to json, I want to pass the NSArray inside the NSDictionary as a parameter along with the url to server, how it can be done while method is post ? I had tried sample codes but not found my exact solution.below is my sample code
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:#"contact_name", #"kumar",#"designantion",#"sales", nil];
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:dict, #"OfficeContactPerson", nil];
NSString *post =[[NSString alloc]initWithFormat:#"name=%#&short_name=%#&shop_no=%#&door_no=%#&floor=%#&building=%#&street=%#&area=%#&main=%#&city=%#&state=%#&district=%#&pincode=%#&telephone=%#&contact_name=%#&designatio=%#&mobile=%#&email=%#&OfficeContactPerson=%#",self.txtshowroom.text,self.txtshortname.text,self.txtshop.text,self.txtdoor.text,self.txtfloor.text,self.txtbuilding.text,self.txtstreet.text,self.txtarea.text,self.txtmain.text,cityineger,stateintegervalue,districtintegervalue,self.txtpincode.text,self.txttel.text,self.txtname.text,self.txtdesign.text,self.txtmbl.text,self.txtemail.text,finalDict];
NSLog(#"postdata :%#",post);
NSURL *url=[NSURL URLWithString:#"http://139.59.252.34:1337/office"];
NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postlength=[NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[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 (!urlData){
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Error"message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else
{
NSString *responseData=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response data ----->%#",responseData);
NSError *error=nil;
NSDictionary *jsonData=[NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error];
);
}
OfficeContactPerson": [
{
"office": 29,
"contact_name": "Priya",
"designation": "Prop",
"department": "ALL",
"mobile": "1231231231",
"email": "priya#yopmail.com",
"incharge_status": null,
"created_by": null,
"modified_by": null,
"id": 14,
"createdAt": "2016-04-19T13:43:59.000Z",
"updatedAt": "2016-04-19T14:25:36.000Z"
}
]
Convert array into json string or make dictionary of post data than convert it into json string and post string to server. I hope below code will work for you. This code is works fine for me-
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:#"contact_name", #"kumar",#"designantion",#"sales", nil];
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:dict, #"OfficeContactPerson", nil];
NSURL *url=[NSURL URLWithString:#"http://139.59.252.34:1337/office"];
NSData *postData=[[[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:finalDict options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postlength=[NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[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 (!urlData){
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Error"message:[NSString stringWithFormat:#"%ld",(long)(error.code)]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else
{
NSString *responseData=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response data ----->%#",responseData);
NSError *error=nil;
NSDictionary *jsonData=[NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error];
}
I'm new in ios app development but I try to solve.lets assume that these are your string.Try this code:
NSString *messages-getModuleMessages=#"messages-getModuleMessages";
NSString * authtincateToken=#"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtSMDxxxxxxx";
NSString *accessSecretkey =#"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtxxxxxxxx";
NSString *inboxvalue =#"hai thios is textmessage";
// this is your dictionary value are you passed
NSDictionary * callDict = [NSDictionary dictionaryWithObjectsAndKeys:messages-getModuleMessages,#"call",authtincateToken,#"authToken", accessSecretkey, #"accessSecret",inboxvalue,#"calotype",#"json",#"format",nil];
// convert your dictionary to NSData
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callDict options:kNilOptions error:nil];
// this is your service request url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xxxxxxxx"]];
// set the content as format
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
// this is your response type
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
// send the synchronous connection
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
// here add your server response NSJSONSerialization
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
// if u want to check the data in console
NSString *tmp=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", tmp);
Try below line of code and put them place of first two line of line code. Problem is only there.
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:#"contact_name", #"kumar",#"designantion",#"sales", nil];
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSArray arrayWithObject:dict], #"OfficeContactPerson", nil];
NSData *POST_Params = [NSJSONSerialization dataWithJSONObject:urlParams options:NSJSONWritingPrettyPrinted error:nil]; // Pass these post data in request
Hope this will work for you!!

Passing parameters to the JSON Post method in nil

NSString *Str = #"Basic YnRwaXhlbDoxMjM0NQ==";
NSArray *keys = [NSArray arrayWithObjects: #"Authorization",nil];
NSArray *objects = [NSArray arrayWithObjects:Str,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONReadingMutableContainers error:&error];
NSURL *urlStr1 = [NSURL URLWithString:#"http://192.168.0.49/bubbletop/index.php?route=feed/rest_api/gettoken&grant_type=client_credentials"];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] initWithURL:urlStr1];
[request1 setHTTPMethod:#"POST"];
[request1 setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request1 setHTTPBody: jsonData];
_connection = [[NSURLConnection alloc]initWithRequest:request1 delegate:self startImmediately:YES];
NSData *data1 = [NSData dataWithContentsOfURL:urlStr1];
NSDictionary *fashionJson = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:nil];
NSLog(#"requestReply: %#", fashionJson);
Here i'm passing the header field parameter as Basic YnRwaXhlbDoxMjM0NQ== for the key Authorization but getting the data as nil and getting log as
requestReply: (null)
I think you were added header field as wrong
not like
NSString *Str = #"Basic YnRwaXhlbDoxMjM0NQ==";
NSArray *keys = [NSArray arrayWithObjects: #"Authorization",nil];
NSArray *objects = [NSArray arrayWithObjects:Str,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONReadingMutableContainers error:&error];
do like as HTTP token authentication
[request1 addValue:#"Basic YnRwaXhlbDoxMjM0NQ==" forHTTPHeaderField:#"Authorization"];
Note
no need of append body in here
[request1 setHTTPBody: jsonData];
for sample request see this
Since you are using NSData *data1 = [NSData dataWithContentsOfURL:urlStr1]; method, it will not take your httpbody from the url request you created. Either implement NSURLConnection delegate methods or use NSURLSession to load the data. Since NSURLConnection API is deprecated, I would recommend NSURLSession.

Proper JSON encoding for HTTP POST request in iOS

Posted a query previously about JSON parsing not working properly. Did more looking into it with a packet sniffer and also with another client that works properly and found out it's a syntax thing, that I still can't seem to solve.
The code in the bottom makes the HTTP request to have the JSON in it as:
{"key":"value"}
And my server is actually looking for a JSON in the following syntax:
key=%22value%22
I tried to write some code that does this manually, but figured there must be something out of the box for iOS, and I don't want to have faults in the future.
I messed around with it for a while trying to find the right code for the job, but couldn't (you can see some code I tried commented out). Can anyone help me?
+ (NSString*)makePostCall:(NSString*)urlSuffix
keys:(NSArray*)keys
objects:(NSArray*)objects{
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
// NSString *dataString = [self getDataStringFromDictionary:params];
// NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
// NSLog(#"%#", jsonObject);
if (!jsonData) {
// should not happen
NSError *error;
NSLog(#"Got an error parsing the parameters: %#", error);
return nil;
} else {
// NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(#"%#", jsonRequest);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", urlPrefix, urlSuffix]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// TODO: handle error somehow
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return returnString;
}
}

How to reach members of json with iOS

I want to reach from ios to a .net .asmx web service, and I reach with the following code:
NSString *urlString = #"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
//...do something with the returned value
}
It returns clean json {"hellom":"Hello World","hellom2":"HelloWorld2"} but I can't reach members and value one by one
How can I do that?
You can convert JSON data into an object by using the following code...
NSData *jsonData = ... the data you got from the server
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
object will then be a NSDictionary like this...
#{
hellom : #"Hello World",
hellom2: #"HelloWorld2"
}
You can then get to the keys and values like any other dictionary.

Send JSON post data from iPhone Application Expressjs/Nodejs backend

This is my code for sending a post request to a nodejs backend.
CLLocation* location = [locationManager location];
CLLocationCoordinate2D coord = [location coordinate];
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://50.63.172.74:8080/points"]];
//[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSDictionary* jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:coord.latitude], #"lat", [NSNumber numberWithFloat:coord.longitude], #"lng", nil];//dictionaryWithObjectsAndKeys:coord.latitude, nil]
NSString *postString;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
Using express I'm getting the request.body back on the server but it looks like this:
{ '{\n "lat" : 0.0,\n "lng" : 0.0\n}': '' }
and I can't access it by just saying request.body.lat since it comes back as undefined.
I want the body to look like:
{ "lat":0.0, "lng":0.0}
Any idea on how to do that using express?
May this help you.
Please replace 0.0 with your actual coordiantes
NSArray *keys = [NSArray arrayWithObjects:#"lat", #"lng", nil];
NSArray *objects = [NSArray arrayWithObjects:#"0.0",#"0.0", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData ;
NSString *jsonString;
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *requestString = [NSString stringWithFormat:
#"http://50.63.172.74:8080/points"];
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
NSLog(#"Error %#",errorReturned.description);
}
else
{
NSError *jsonParsingError = nil;
NSMutableArray *arrDoctorInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSLog(#"Dict %#",arrDoctorInfo);
}
The problem is that after you use NSJSONSerialization to obtain a NSData object containing your JSON data, you then create postString from that data. Eliminate that unnecessary step, and just do:
[request setHTTPBody:jsonData];
And you should get the expected JSON in your server-side code.

Resources