Search code examples
swiftlocalizationlocalecountry-codes

Retrieve country name using country code in app language not phone locale language


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?


Solution

  • 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"