Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting country name from country code

Tags:

swift

location

I have found the answer for this for objective-c but Im having a hard time doing this in swift.

I have used this to get the country code for the current location:

     let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String
    print(countryCode)
// printing for example US

But how do I convert this country code to a country name, like in this example converting "US" to "United States"?

like image 253
Tarjerw Avatar asked Feb 28 '16 12:02

Tarjerw


People also ask

Is there a 3 letter country code?

ISO 3166-1 alpha-3 codes are three-letter country codes defined in ISO 3166-1, part of the ISO 3166 standard published by the International Organization for Standardization (ISO), to represent countries, dependent territories, and special areas of geographical interest.

What is the 3 digit country code for USA?

Member countries of the North American Numbering Plan (NANP) are assigned three-digit area codes under the common country prefix 1, shown in the format +1 XXX. +1 – United States, including United States territories: +1 340 – United States Virgin Islands.


1 Answers

A super clean Swift 3 version would be:

func countryName(countryCode: String) -> String? {
    let current = Locale(identifier: "en_US")
    return current.localizedString(forRegionCode: countryCode)
}

You can change the locale identifier to eg. Locale.current.identifier if you want localized names. The example above is for English only.

like image 175
Daniel Avatar answered Sep 20 '22 22:09

Daniel