Leem.fin
Leem.fin

Reputation: 42582

get NSLocale from country name

I am developing iOS with Swift 3.

I got country name string like "Japan", "Britain", "Spain", etc.

I am wondering what is the best way to generate NSLocale instance out from the country name?

I only found localizedString(forCountryCode:) in document, it means I have to manually parse country name to country code in my project like below:

switch countryName
{
     case "Spain":
          "ES"
}

Is there better way to generate locale from country name?

Upvotes: 0

Views: 987

Answers (1)

maxkoriakin
maxkoriakin

Reputation: 337

You can use CoreLocation framework. This code create a dictionary, where name of country is key, and ISO is value

    var dictionary = [String : String]()
    let arrayWithCodes = Locale.isoRegionCodes
    for code in arrayWithCodes {
        let description = Locale.current.localizedString(forRegionCode: code)
        if description != nil {
            dictionary[description!] = code
        }
    }

Upvotes: 2

Related Questions