Reverse geocoding to return results only in English?

旧城冷巷雨未停 提交于 2019-11-28 01:10:26

You have to use the NSLocale class that manages info in every language. Then for your final translation you have to force the locale to be in english language:

CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:myCurrentLocation completionHandler:^(NSArray *placemarks, NSError *error) {

    for (CLPlacemark * placemark in placemarks) {
         //Obtains the country code, that is the same whatever language you are working with (US, ES, IT ...)
         NSString *countryCode = [placemark ISOcountryCode];
         //Obtains a locale identifier. This will handle every language
         NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]];
         //Obtains the country name from the locale BUT IN ENGLISH (you can set it as "en_UK" also)
         NSString *country = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] displayNameForKey: NSLocaleIdentifier value:identifier];

        //Continues your code
        [locationController setLastKnownCountry:country];
    }
}];

It works with the iOS 11 API: reverseGeocodeLocation(_:preferredLocale:completionHandler:)

Sadly I need to support other iOS versions and changing the UserDefaults does neither feel good nor work for me :-(

You can try the below code to extract the name of the country from the placemark which will show the result in english only regardless the county name

- (void)findAddress:(CLLocationDegrees)latitude with:(CLLocationDegrees)longitude
{
    CLLocation *location =[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"Finding address");
        if (error) {
            NSLog(@"Error %@", error.description);
        } else {
            NSLog(@"%@",[placemarks valueForKey:@"country"]);
        }
    }];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!