0

In my project users cant go to the next view unless they are currently in a specific city. So here is how I check the city of a coordinates

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)
        }
    }
}

then when users click on get my current locations I take the coordinates and check:

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

the problem is I have to check the name of the city in all the languages because the output of the city name depends on the language of the device ( As I found out during testing) and it's just not right. Is there any way other than this to check the name of the city in all languages?

Riajur Rahman
  • 1,976
  • 19
  • 28
AlmoDev
  • 969
  • 2
  • 18
  • 46

1 Answers1

1

You can use NSLocalizedString to get name of Riyadh in the user's language. This requires translation you to enter the name Riyadh in a whole bunch of languages. Wikipedia can lend you a hand without the need for professional translator.

Another approach is to obtain a placemark that you know is within the city, then compare that palcemark's city to what the user entered. This way, both city names are in the user's language:

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)
    }
}

When you check the placemark obtained from user's inputs:

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)")
    }
}

The annoyance of this approach is riyadh may not be initialized if you need it very early on in the view controller's lifecycle.

Code Different
  • 90,614
  • 16
  • 144
  • 163
  • Thank you for your answer. I'd rather pick the first approach with `NSLocalizedString` But I need help with that. Do you know any resources? – AlmoDev Dec 28 '17 at 09:11