Reputation:
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"}
Upvotes: 1
Views: 3988
Reputation: 13057
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];
}
Upvotes: 6