Skip to content

Instantly share code, notes, and snippets.

@mikeyk
Created October 27, 2009 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeyk/219350 to your computer and use it in GitHub Desktop.
Save mikeyk/219350 to your computer and use it in GitHub Desktop.
- (NSString *)stringFromURL:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (error) {
return @"connection error";
} else {
// Construct a String around the Data from the response
return [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding] autorelease];
}
}
- (void) doRequest: (NSURL *) url {
NSString * jsonString = [self stringFromURL:url];
NSDictionary * response = (NSDictionary*)[jsonString yajl_JSON];
if (response == nil) {
if (![self.hasFailedConnection boolValue]){
[self setHasFailedConnection:[NSNumber numberWithInt:1]];
[delegate networkError];
}
} else {
if([response valueForKey:@"num_results"] == 0){
// TODO handle no results
}
else if([response valueForKey:@"latitude_delta"] && [response valueForKey:@"longitude_delta"]
&& [response objectForKey:@"result_set"]) {
lastResultList = [[NSArray alloc] initWithArray:[response objectForKey:@"result_set"]];
MKCoordinateRegion region_ = region;
region_.span.latitudeDelta = [[response valueForKey:@"latitude_delta"] floatValue];
region_.span.longitudeDelta = [[response valueForKey:@"longitude_delta"] floatValue];
[self setRegion:region_];
[self performSelectorOnMainThread:@selector(receivedResults) withObject:nil waitUntilDone:NO];
} else {
if ([self.hasFailedConnection boolValue] == NO){
[delegate networkError];
}
}
}
}
- (BOOL) fetchesMoreResults {
return YES;
}
- (void) fetchData: (NSURL *) url {
NSInvocationOperation * io = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doRequest:) object:url] autorelease];
[opQueue addOperation:io];
}
- (void) receivedResults {
[locations removeAllObjects];
for (NSDictionary * cur in lastResultList) {
NSString * category = [cur valueForKey:@"category"];
BOOL meetsFilter = YES;
if ([filters objectForKey:category]!=nil) {
meetsFilter = [[filters objectForKey:category] boolValue];
}
if (meetsFilter) {
float lat = [[cur valueForKey:@"lat"] floatValue];
float lon = [[cur valueForKey:@"lon"] floatValue];
CLLocationCoordinate2D coord;
coord.latitude = lat;
coord.longitude = lon;
InfoLocation * newInfoLoc = [[InfoLocation alloc] initWithCoordinate:coord info:cur];
[locations addObject:newInfoLoc];
[newInfoLoc release];
}
}
[delegate resultsAvailable];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment