Подтвердить что ты не робот

Как локализовать результат адреса из reverseGeocodeLocation?

Мое приложение iphone должно разрешить адрес, основанный на широте и долготе пользователя. reverseGeocodeLocation работает отлично, но результаты на английском языке.

Есть ли способ локализовать результаты на других языках?

не удалось найти информацию об этом в яблоке или в другом месте.

Используемый мной код:

CLGeocoder *geocoder = [[[CLGeocoder alloc] init] autorelease];
CLLocation *location = [[[CLLocation alloc] 
       initWithLatitude:coord.latitude longitude:coord.longitude] autorelease];

[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
    NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");

    if (error){
        NSLog(@"Geocode failed with error: %@", error);
        [self displayError:error];
        return;
    }
    if(placemarks && placemarks.count > 0)
    {
      //do something
        CLPlacemark *topResult = [placemarks objectAtIndex:0];

        NSString *addressTxt = [NSString stringWithFormat:@"%@ %@,%@ %@", 
           [topResult subThoroughfare],[topResult thoroughfare],
           [topResult locality], [topResult administrativeArea]];
    }
}
4b9b3361

Ответ 1

Я нашел, как локализовать название страны, возможно, это поможет:

CLPlacemark *placemark;

NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: placemark.ISOcountryCode forKey: NSLocaleCountryCode]];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString *country = [usLocale displayNameForKey: NSLocaleIdentifier value: identifier];

вставить любой идентификатор страны вместо @ "en_US"

Ответ 2

Mattt Thompson имеет отличную запись при использовании метод из AddressBookUI.framework для локализации адресов на его сайте NSHipster. Он также имеет библиотеку форматирования на github, которая содержит класс для этого типа локализации, который использует описанный им метод AddressBookUI.framework.

Ответ 3

Начиная с iOS11, Apple предоставляет нам другой API, который может установить локаль для печати локализованного языка.

- (void)reverseGeocodeLocation:(CLLocation *)location preferredLocale:(nullable NSLocale *)locale
 completionHandler:(CLGeocodeCompletionHandler)completionHandler API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));

Ответ 4

Решение для Swift 4, iOS 11

Вы можете принудительно получить результаты геокодирования на выбранном языке локали, установив аргумент preferredLocale: Locale.init(identifier: "en_US").

CLGeocoder().reverseGeocodeLocation(location, preferredLocale: Locale.init(identifier: "en_US"), completionHandler: {(placemarks, error) -> Void in
    print(location)

    if error != nil {
        print("Reverse geocoder failed with error" + error!.localizedDescription)
        return
    }

    if placemarks!.count > 0 {
        let pm = placemarks![0]
        print(pm.administrativeArea!, pm.locality!)
    }
    else {
        print("Problem with the data received from geocoder")
    }
})