NSLocale countryCode is 419

Hello,

Upon registration to be able to localise the App for the users I am requesting the countryCode:

(Locale.current as NSLocale).object(forKey: NSLocale.Key.countryCode) as? String

Most of the values are the one expected ("US", "GB", "DE", ...), however in some cases I have numeric country codes like "419" or "241".

I wanted to know if this was expected and how I can make them fallback to the regular country code that are none numeric.

Thank you

Hi, I’d recommend using Locale.current.region which has many known values https://developer.apple.com/documentation/foundation/locale/region#4063083

The locale cannot return a specific country, as for instance es_419 corresponds to Spanish in Latin America, so a variant used across multiple countries.

Bundle.preferredLocalizations(from: availableLocalizations, forPreferences: initialOrPreferredLocalization).first can compute fallbacks for you. https://developer.apple.com/documentation/foundation/bundle/1409418-preferredlocalizations

Thanks very much for your prompt answer, will deep dive in the shared documentation and try it!

So this code:

let nsLocale = (Locale.current as NSLocale)
let countryCode = nsLocale.object(forKey: NSLocale.Key.countryCode) as? String
let languageCode = nsLocale.object(forKey: NSLocale.Key.languageCode) as? String
let currencyCode = nsLocale.object(forKey: NSLocale.Key.currencyCode) as? String
let localeCountryCode = nsLocale.countryCode
let systemLocaleCountryCode = nsLocale.countryCode
return """
    Given countryCode: \(countryCode ?? "error")
    languageCode: \(languageCode ?? "error")
    currencyCode: \(currencyCode ?? "error")
    otherCountryCode: \(localeCountryCode ?? "error")
    systemCountryCode: \(systemLocaleCountryCode ?? "error")
"""

Give this output sometimes:

 Given countryCode: 419
languageCode: en
currencyCode: error
otherCountryCode: 419
systemCountryCode: 419

And I don't understand why this would be the case.

Would you have any idea? Do you know what I can add to try to have a more accurate debugging?

Thank you

NSLocale countryCode is 419
 
 
Q