24

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

Tarjerw
  • 505
  • 1
  • 5
  • 12
  • you can take a look at https://github.com/funky-monkey/IsoCountryCodes – olyv Aug 08 '19 at 08:44
  • You can use this one. It's a complete module, built by Swift & Firebase. But it's not free. https://codecanyon.net/item/country-picker-ios/25414188 – Tulon Mar 16 '20 at 06:17

9 Answers9

47

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.

Daniel
  • 643
  • 7
  • 7
39

Swift 3

func countryName(from countryCode: String) -> String {
    if let name = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: countryCode) {
        // Country name was found
        return name
    } else {
        // Country name cannot be found
        return countryCode
    }
}
AlBeebe
  • 8,101
  • 3
  • 51
  • 65
9

Try doing something like this:

// get the localized country name (in my case, it's US English)
let englishLocale = Locale.init(identifier: "en_US")

// get the current locale
let currentLocale = Locale.current

var theEnglishName : String? = englishLocale.displayName(forKey: NSLocaleIdentifier, value: currentLocale.localeIdentifier)
if let theEnglishName = theEnglishName
{
    let countryName = theEnglishName.sliceFrom("(", to: ")")
    print("the localized country name is \(countryName)")
}

with this helper function that I found here:

import Foundation

extension String {
    func sliceFrom(start: String, to: String) -> String? {
        return (rangeOfString(start)?.endIndex).flatMap { sInd in
            (rangeOfString(to, range: sInd..<endIndex)?.startIndex).map { eInd in
                substringWithRange(sInd..<eInd)
            }
        }
    }
}

I figured this out by researching into this related question.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • This answer definitely works but on the top part Swift 4.2 doesn't have a 'sliceFrom' function anymore. Instead use 'replacingOccurrences' like so: theEnglishName.replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: ""). https://stackoverflow.com/a/53839473/4833705 – Lance Samaria Dec 18 '18 at 19:02
6

Here is a compact swift 4 version that has been working for me:

func countryCode(from countryName: String) -> String? {
    return NSLocale.isoCountryCodes.first { (code) -> Bool in
        let name = NSLocale.current.localizedString(forRegionCode: code)
        return name == countryName
    }
}

or an elegant extension like @Memon suggests:

extension Locale {

    func countryCode(from countryName: String) -> String? {
        return NSLocale.isoCountryCodes.first { (code) -> Bool in
            let name = self.localizedString(forRegionCode: code)
            return name == countryName
        }
    }

}
lorenzo
  • 1,487
  • 1
  • 17
  • 25
1

If you want to print the country name and country flag here is the code

func countryInformation(countryCode:String){
        
        var flag: String? = ""
        let flagBaseCode = UnicodeScalar("").value - UnicodeScalar("A").value
        countryCode.uppercased().unicodeScalars.forEach {
            if let scaler = UnicodeScalar(flagBaseCode + $0.value) {
                flag?.append(String(describing: scaler))
            }
        }
        if flag?.count != 1 {
            flag = nil
        }
        
        let countryName = Locale.current.localizedString(forRegionCode: countryCode)
        print(countryName ?? "No name")
        print(flag ?? "No flag")
        print(countryCode)
        
    }

How to use

let regionCode = Locale.current.regionCode ?? "ae"
countryInformation(countryCode: regionCode)

Output will be:

United Arab Emirates

AE
Rashid Latif
  • 2,809
  • 22
  • 26
0

Try this

let countryLocale : NSLocale =  NSLocale.currentLocale()
            let countryCode  = countryLocale.objectForKey(NSLocaleCountryCode)// as! String
            let country = countryLocale.displayNameForKey(NSLocaleCountryCode, value: countryCode!)
            print("Country Locale:\(countryLocale)  Code:\(countryCode) Name:\(country)")
Binoy jose
  • 461
  • 4
  • 9
0

Working on Swift3

import Foundation

  extension String {
      func sliceFrom(start: String, to: String) -> String? {
           return (range(of: start)?.upperBound).flatMap({ (sInd) -> String? in
                   (range(of: to, range: sInd..<endIndex)?.lowerBound).map { eInd in
                      substring(with: sInd..<eInd)
         } 
     })
    }
   }   

Use in app delegate

        let englishLocale : NSLocale = NSLocale.init(localeIdentifier :  "en_US")

    // get the current locale
    let currentLocale = NSLocale.current

    var theEnglishName : String? = englishLocale.displayName(forKey: NSLocale.Key.identifier, value: currentLocale.identifier)
    if let theEnglishName = theEnglishName
    {
        countryName = theEnglishName.sliceFrom(start: "(", to: ")")
        print("the localized country name is \(countryName)")
    }
Memon Irshad
  • 972
  • 1
  • 8
  • 17
0

Swift 4

struct CountryCode {
    let country: String?
    let code: String
}

let countries: [CountryCode] = NSLocale.isoCountryCodes.map { 
    let country = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: $0)
    return CountryCode(country: country, code: $0) 
}

countries.map { print($0) }

// Prints 
// CountryCode(country: Optional("Ascension Island"), code: "AC")
// CountryCode(country: Optional("Andorra"), code: "AD")
// CountryCode(country: Optional("United Arab Emirates"), code: "AE")
// CountryCode(country: Optional("Afghanistan"), code: "AF")
andromedainiative
  • 4,414
  • 6
  • 22
  • 34
  • Do not use `NSLocale` in Swift 3 or 4. The answer by Daniel shows the proper solution and it works just fine in Swift 4. – rmaddy Oct 11 '18 at 22:06
-1

Swift 3

   let currentLocale : NSLocale = NSLocale.init(localeIdentifier :  NSLocale.current.identifier)
   let countryName : String? = currentLocale.displayName(forKey: NSLocale.Key.countryCode, value: countryCode)
  print(countryName ?? "Invalid country code")

Note: If you manually entered localIdentifier means iOS 8 not listed all country name (Eg: "en_US")

FelixSFD
  • 6,052
  • 10
  • 43
  • 117