Search code examples
iosobjective-ccllocationmanagercllocationclgeocoder

Why use CLGeocoder with an array of "placemarks"?


When trying to use CLGeocoder, I got this example from an online tutorial: https://www.appcoda.com/how-to-get-current-location-iphone-user/

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil) {
        longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
        latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    }

    // Reverse Geocoding
    NSLog(@"Resolving the Address");
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
        if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];
            addressLabel.text = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
                                 placemark.subThoroughfare, placemark.thoroughfare,
                                 placemark.postalCode, placemark.locality,
                                 placemark.administrativeArea,
                                 placemark.country];
        } else {
            NSLog(@"%@", error.debugDescription);
        }
    } ];

}

However, I don't quite understand why it takes an array of "placemarks" in the completion handler part and why we should use the last object of "placemarks" (I also see people using the first object?).

I've read through the apple document but didn't find any good explanation in terms of use: https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLGeocoder_class/


Solution

  • You are reverse-geocoding a lat/long. It might yield more than one address. If you get more than one and don't care which one you use, it's just as valid to extract the first or last placemark object in the array.

    (You'll probably only get one match most of the time, in which case the first and last element are the same thing.)