As with most APIs the first thing you need to do is head over to http://www.bing.com/developers/createapp.aspx to create an ID to access it. Then go to http://code.google.com/p/json-framework/ to grab the JSON framework and add the JSON folder into your Xcode project, preferably in the Classes group.
Now we need a method to call the API over HTTP which can be done with the following.
- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
[urlRequest release];
[response release];
[error release];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
Now to work with the JSON response we make sure we can access the JSON framework by placing this line with your other import directives.
#import "SBJSON.h"
The following method will return a NSArray of NSDictionary results.
- (NSArray *)getResults:(NSString *)serviceMethod
{
SBJSON *jsonParser = [SBJSON new];
NSError *error;
NSURL *apiCall = [NSURL URLWithString:serviceMethod];
NSString *jsonDocument = [self stringWithUrl:apiCall];
NSDictionary *jsonObject = (NSDictionary *)[jsonParser objectWithString:jsonDocument error:&error];
NSDictionary *response = (NSDictionary *)[jsonObject valueForKey:@"SearchResponse"];
NSDictionary *results = (NSDictionary *)[response valueForKey:@"Phonebook"];
NSArray *resultsArray = [results valueForKey:@"Results"];
[jsonParser release];
[error release];
[jsonDocument release];
[jsonObject release];
[response release];
[results release];
return resultsArray;
}
Finally a simple example of its usage.
NSArray *results = [self getResults:@"http://api.search.live.net/json.aspx?sources=phonebook&Appid=YOUR APPID&query=schools&Latitude=39.949535&Longitude=-75.143814&Radius=2.5&Phonebook.Count=8&Phonebook.Offset=0&Phonebook.FileType=YP&Phonebook.SortBy=Distance"];
for(NSDictionary *result in results)
{
NSLog([result valueForKey:@"Title"]);
}