从国家代码中获取国家名称

问题描述 投票:0回答:9

我已经找到了 objective-c 的答案,但我很难快速做到这一点。

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

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

但是我如何将这个国家代码转换为国家名称,就像在这个例子中将“US”转换为“United States”?

swift location
9个回答
46
投票

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

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

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


39
投票

斯威夫特 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
    }
}

9
投票

尝试做这样的事情:

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

我在这里找到的这个辅助函数

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 弄明白了这一点。


6
投票

这是一个紧凑的 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
        }
    }

}

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

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

在应用委托中使用

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

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

0
投票

如果要打印国名和国旗这里是代码

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

使用方法

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

输出将是:

United Arab Emirates
🇦🇪
AE

-1
投票

斯威夫特 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未列出所有国家/地区名称(例如:“en_US”)

© www.soinside.com 2019 - 2024. All rights reserved.