Search code examples
iosswift4cllocationmanagercllocationnslocalizedstring

how to localize language of the city with location in swift 4 for ios 9.0?


I used location in my app that will get latitude and longitude in the app and then can give me the name of the city that user is in the name is in English but I want to convert that to the Persian I found this method But this will work in iOS 11 But I am developing from ios9 how can I get print of the current city in Persian ? here I my codes

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if firstUpdate {
        if let _latitude = locations.first?.coordinate.latitude {
            if let _longitude = locations.first?.coordinate.longitude {
                firstUpdate = false
                self.locationManager.stopUpdatingLocation()
                self.carregaDadosLocal(latitude: _latitude, longitude: _longitude)
                let location = CLLocation(latitude: _latitude, longitude: _longitude)
                if #available(iOS 11.0, *) {
                    CLGeocoder().reverseGeocodeLocation(location, preferredLocale: Locale(identifier: "fa_IR")) { (local, error) in

                        if (local?[0]) != nil {

                            print(local?[0].thoroughfare!)
                            print(local?[0].locality)
                            print(local?[0].location)
                            print(local?[0].subLocality)

                        }
                    }
                } else {
                    // Fallback on earlier versions
                }
            }
        }
    }
}

Solution

  • On iOS 9, you can temporarily override the app's language:

    func completionHandler(_ placemarks: [CLPlacemark]?, _ error: Error?) {
        if let place = placemarks?.first {
            print(place.thoroughfare!)
            print(place.locality)
            print(place.location)
            print(place.subLocality)
        }
    }
    
    let location = CLLocation(latitude: 48.858370, longitude: 2.294481)
    if #available(iOS 11.0, *) {
        CLGeocoder().reverseGeocodeLocation(location, preferredLocale: Locale(identifier: "fa_IR"), completionHandler: completionHandler)
    } else {
        UserDefaults.standard.set(["fa_IR"], forKey: "AppleLanguages")
        CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in
            // Remove the language override
            UserDefaults.standard.removeObject(forKey: "AppleLanguages")
            completionHandler(placemarks, error)
        }
    }
    

    The catch is that there's a brief period of time your app becomes Persian, regardless of user settings. Anything that depends on locale (like NSLocalizedString or NumberFormatter) will be affected.