从国家/地区代码获取国名

时间:2016-02-28 12:31:06

标签: swift location

我已经为Objective-c找到了答案,但我很难在swift中做到这一点。

我用它来获取当前位置的国家/地区代码:

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

但是如何将此国家/地区代码转换为国家/地区名称,例如在此示例中将“US”转换为“美国”?

8 个答案:

答案 0 :(得分:22)

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

答案 1 :(得分:18)

超级干净的 Swift 3 版本将是:

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

您可以将区域设置标识符更改为例如。如果您想要本地化名称,请使用Locale.current.identifier。以上示例仅适用于英语。

答案 2 :(得分:8)

尝试做这样的事情:

// 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)")
}

使用此辅助函数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)
            }
        }
    }
}

我通过研究this related question来解决这个问题。

答案 3 :(得分:0)

试试这个

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

答案 4 :(得分:0)

使用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)
         } 
     })
    }
   }   

在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)")
    }

答案 5 :(得分:0)

快捷键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")

答案 6 :(得分:0)

这是一个紧凑的 swift 4 版本,对我有用:

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

或像@Memon所建议的那样优雅的扩展名

extension Locale {

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

}

答案 7 :(得分:-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")

注意:如果您手动输入localIdentifier表示iOS 8未列出所有国家/地区名称(例如:&#34; en_US&#34;)