PDA

View Full Version : Tried getting city from location data... weirdness ensued




MaxFreud
Jan 28, 2011, 09:12 PM
Hi all,

I'm trying to determine what city my app is being run in.
I'm doing the standard CLLocationManager thing to get the location data:

myLocationManager = [[CLLocationManager alloc] init];
[myLocationManager setDelegate:self];
[myLocationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
[myLocationManager setDistanceFilter:1000];
[myLocationManager startUpdatingLocation];


Then I'm using the MKReverseGeocoder to get the name of the city:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if(manager == myLocationManager)
{
NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 60.0)
{
NSLog(@"Attempting to extract city name from current location");
theGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
theGeocoder.delegate = self;
[theGeocoder start];
myLocationManager.delegate = nil;
}
}
}

And I'm getting some weird results. First of all, sometimes the MKReverseGeocoder instance will call the delegate method -(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark indicating that it succeeded. However, not all of the fields in the MKPlacemark object are filled. Specifically, I need the locality property, and a lot of times, it's null... even when the other fields have been filled correctly.

Secondly, more often than not, the geocoder wil fail with [error description] Error Domain=MKErrorDomain Code=4 "The operation couldn’t be completed. (MKErrorDomain error 4.)"

I really don't understand the erratic response of the geocoder. Either I'm doing something wrong and shouldn't be getting good results, or I'm doing it right and should be getting results... I don't understand how it can sometimes work and sometimes not. About every 5th time I run it, it will actually detect the city correctly.

Spare a brother some MapKit wisdom?