Reputation: 1614
I'm using Localize_Swift
library. I change the app language using it. Now I'm retrieving country name using country code using this.
class Country: NSObject {
class func locale(for countryCode : String) -> String {
let identifier = NSLocale(localeIdentifier: countryCode)
let countryName = identifier.displayName(forKey: NSLocale.Key.countryCode, value: countryCode)
return countryName?.uppercased() ?? ""
}
}
The function is returning the country name in the phone locale language and not the app language. Is there a way to make it return the country name in the its locale language name.
Example: Germany -> Deutschland
Example: Austria -> Österreich
Or any suggestions for a work around?
Upvotes: 0
Views: 1516
Reputation: 3
Leaving this here for those using iOS16+. You can now make use of 'Locale' like so:
Locale.current.localizedString(forRegionCode: "fr")
... which will then output:
Optional("France")
Or altenatively, you could do the following to get an array with all country names:
Locale.Region.isoRegions.compactMap { Locale.current.localizedString(forRegionCode: $0.identifier) }
Upvotes: 0
Reputation: 236498
You just need to specify the language when initializing your Locale:
struct Country {
static func locale(for regionCode: String, language: String = "en") -> String? {
Locale(identifier: language + "_" + regionCode)
.localizedString(forRegionCode: regionCode)
}
}
Country.locale(for: "DE") // "Germany"
Country.locale(for: "DE", language: "de") // "Deutschland"
If you would like to automatically select the language based on the country/region code:
struct Country {
static func locale(for regionCode: String) -> String? {
let languageCode = Locale(identifier: regionCode).languageCode ?? "en"
return Locale(identifier: languageCode + "_" + regionCode)
.localizedString(forRegionCode: regionCode)
}
}
Country.locale(for: "DE") // "Deutschland"
Upvotes: 2