Getting country name from country code

2020-02-10 20:54发布

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

8条回答
Root(大扎)
2楼-- · 2020-02-10 21:47

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)")
查看更多
欢心
3楼-- · 2020-02-10 21:49

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
        }
    }

}
查看更多
登录 后发表回答