iOS Swift:如何获取指定语言城市名及阿拉伯语位置详情(含代码)
如何在iOS Swift 3中获取指定语言的城市名称?
看起来你踩了个小坑——accessibilityLanguage属性根本不是用来控制地址解析结果语言的,它是给VoiceOver这类辅助功能用的,和我们要的地址本地化完全不搭边。下面给你两种靠谱的解决方案:
方案一:用CLGeocoder的Locale属性指定语言
在Swift 3对应的iOS版本里,直接给CLGeocoder设置locale就能指定返回地址的语言,阿拉伯语的话用"ar"作为标识符就行。修改后的代码如下:
func fetchCountryAndCity(location: CLLocation, completion: @escaping (String, String, String) -> ()) { let geo : CLGeocoder = CLGeocoder() // 设置阿拉伯语Locale,替换掉没用的accessibilityLanguage geo.locale = Locale(identifier: "ar") geo.reverseGeocodeLocation(location) { placemarks, error in if let error = error { print(error) completion("", "", "") // 别忘了给错误情况补全回调,避免调用方一直等 return } guard let placemark = placemarks?.first else { completion("", "", "") return } let country = placemark.country ?? "" let city = placemark.locality ?? "" let administrativeArea = placemark.administrativeArea ?? "" // 对应你代码里的第三个返回值 completion(country, city, administrativeArea) } }
小提示:如果你的APP要兼容iOS 11及以上,还可以用reverseGeocodeLocation(_:preferredLocale:completionHandler:)方法,直接把Locale传进去,效果是一样的。另外要注意,部分地区的地址数据可能没有完全本地化的阿拉伯语翻译,这种情况下还是会返回英文结果。
方案二:用Google Maps的GMSGeocoder(如果已集成SDK)
你之前注释掉了GMSGeocoder,其实它的地址本地化数据覆盖得更全,尤其是阿拉伯语这类非英语地区的解析结果会更准确。代码示例如下:
import GoogleMaps func fetchCountryAndCityWithGoogle(location: CLLocation, completion: @escaping (String, String, String) -> ()) { let geocoder = GMSGeocoder() let arabicLocale = Locale(identifier: "ar") geocoder.reverseGeocodeCoordinate(location.coordinate, locale: arabicLocale) { response, error in if let error = error { print(error) completion("", "", "") return } guard let result = response?.firstResult() else { completion("", "", "") return } let country = result.country ?? "" let city = result.locality ?? "" let administrativeArea = result.administrativeArea ?? "" completion(country, city, administrativeArea) } }
最后再啰嗦一句:不管用哪种方法,一定要处理placemarks或result为空的情况,避免出现崩溃哦!
内容的提问来源于stack exchange,提问作者user9329742




