How to get the complete ZIP code through the GPS of the mobile phone

Asked

Viewed 2,497 times

3

I’m trying to get the full zip code through my location using the GPS of my mobile in Objective-C, but it returns only 5 digits. I used the following code snippet:

NSString *cepcompleto = [NSString stringWithFormat:@"%@-%@", placemark.postalCode, [placemark.addressDictionary objectForKey:@"PostCodeExtension"]];

Follow the rest of the code:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    CLLocation *currentLocation = newLocation;
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];
            NSString *cepcompleto = [NSString stringWithFormat:@"%@-%@", placemark.postalCode, [placemark.addressDictionary objectForKey:@"PostCodeExtension"]];

            digitoCep = [placemark.addressDictionary objectForKey:@"PostCodeExtension"];
            cepEstatico = cepcompleto;

            [vg setCep];
        } else {
            NSLog(@"%@", error.debugDescription);
        }
    }];
    [manager startUpdatingLocation];
}
  • 2

    Five digits? Looks like the American standard. Really I don’t know what this object is placemark.addressDictionary, post more code details, this is an API?

  • Perhaps the additional information of this answer help you.

  • 1

    Yes it is an API, I found some examples similar to mine, but it was occurring the same problem, in certain points it displayed the complete cep.

1 answer

2

Your code is correct. However, the CEP mapping in Brazil is flawed and you may encounter null values in the case of key @"PostCodeExtension". For this reason, I consider it a safer alternative to use the key @"FormattedAddressLines".

Instead of:

NSString *cepcompleto = [NSString stringWithFormat:@"%@-%@", placemark.postalCode, [placemark.addressDictionary objectForKey:@"PostCodeExtension"]];

Try this:

NSString *cepcompleto = [NSString stringWithFormat:@"%@", [placemark.addressDictionary[@"FormattedAddressLines"][3]];

Notice that the key @"FormattedAddressLines" is a NSArray with other values such as address, neighborhood and other values besides the zip code that are formatted in a similar way to what we found in Brazil.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.