7

我使用 CLGeocoder 将 CLLocation 从经度/纬度解码为地名。它工作正常。但是还有一件事困扰着我。当我将设备语言设置为英语时,以下代码的结果:

- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
       fromLocation:(CLLocation *)oldLocation{
       /* We received the new location */
       NSLog(@"Latitude = %f", newLocation.coordinate.latitude);
       NSLog(@"Longitude = %f", newLocation.coordinate.longitude);
       [self.geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray* placemarks, NSError* error){
           MKPlacemark *placemarker = [placemarks objectAtIndex:0];
           NSLog(@"%@",placemarker.locality);
       }];
      [self.locationManager stopUpdatingLocation];

}

以英文显示,如:成都。

当我将设备语言更改为中文时,

placemarker.locality

返回一个汉字值。

但我真正想要的是它总是会返回一个英文字符值(没有中文字符值)。我想这与语言环境有关。有人可以帮忙吗?谢谢。

4

3 回答 3

14

Usually, it is not a good practice to mess with user locales. If the device language is set to Chinese is because the user want to read Chinese characters so, why do you want to show him in English when he already told you that he want Chinese?

Anyway, if for any reason you need to force english, you can trick the geoCoder which uses the standardUserDefaults first language so you can do something like this just before calling the geoCoder method:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];

This way, geoCoder will give you all the information in english.

However, this will change the user preferences so it is a best approach to give them back to where they were:

NSMutableArray *userDefaultLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];

[self.geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray* placemarks, NSError* error){
       MKPlacemark *placemarker = [placemarks objectAtIndex:0];
       NSLog(@"%@",placemarker.locality);
   }];

[[NSUserDefaults standardUserDefaults] setObject:userDefaultLanguages forKey:@"AppleLanguages"];

As I said, you should really think why you need this, but if you really need this, that would work.

于 2014-01-08T00:59:49.250 回答
5

我找到了一个不错的解决方案

NSString *country = placemark.ISOcountryCode;

无论您的语言环境如何,这都会返回确切的国家/地区。例如,国家将是 @"US" 而不是 @"United States"

于 2013-01-09T07:52:13.747 回答
3

从 ios 11 开始,您可以将 preferredLocale 参数传递给地理编码器的 reverseGeocodeLocation 方法。

在斯威夫特:

geocoder.reverseGeocodeLocation(
  location: CLLocation,
  preferredLocale: Locale?,
  completionHandler: {}
)

首选区域设置值示例:

Locale(identifier: "en_US")
于 2019-10-02T19:26:11.193 回答