仅以英文获取用户的城市

问题描述 投票:0回答:1

在我的项目中,用户无法进入下一个视图,除非他们目前在特定城市。所以这是我如何检查坐标的城市

func fetchCountryAndCity(location: CLLocation, completion: @escaping (String, String) -> ()) {
    CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in
    if let error = error {
        print(error)
    } else if let country = placemarks?.first?.country,
        let city = placemarks?.first?.locality {
            completion(country, city)
        }
    }
}

然后当用户点击获取我当前的位置时,我取坐标并检查:

fetchCountryAndCity(location: location) { country, city in
                print("country:", country)
                print("city:", city)
                if city == "Riyadh" || city == "الرياض" || city == "리야드" || city == "Riyah"  {

问题是我必须检查所有语言的城市名称,因为城市名称的输出取决于设备的语言(正如我在测试期间发现的那样)并且它是不对的。除此之外还有什么方法可以检查所有语言的城市名称吗?

ios swift xcode location swift4
1个回答
1
投票

您可以使用NSLocalizedString以用户的语言获得利雅得的名字。这需要翻译您在一大堆语言中输入名称Riyadh。维基百科可以帮助您,而无需专业翻译。

另一种方法是获取您知道在城市内的地标,然后将该palcemark的城市与用户输入的城市进行比较。这样,两个城市名称都是用户的语言:

var riyadh: (country: String, city: String)?

override func viewDidLoad() {
    // Riyadh's city hall
    fetchCountryAndCity(location: CLLocation(latitude: 24.686212, longitude: 46.712462)) { country, city in
        self.riyadh = (country, city)
    }
}

当您检查从用户输入获得的地标时:

fetchCountryAndCity(location: CLLocation(latitude: 24.647212, longitude: 46.710844)) { country, city in
    if let riyadh = self.riyadh, riyadh == (country, city) {
        print("Hey it's Riyadh. Name in user locale is \(city)")
    }
}

如果您在视图控制器的生命周期中很早就需要它,那么这种方法的烦恼是riyadh可能无法初始化。

© www.soinside.com 2019 - 2024. All rights reserved.