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

Posted

技术标签:

【中文标题】从国家代码中获取国家名称【英文标题】:Getting country name from country code 【发布时间】:2016-06-11 11:43:53 【问题描述】:

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

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

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

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

【问题讨论】:

你可以看看github.com/funky-monkey/IsoCountryCodes 你可以用这个。这是一个完整的模块,由 Swift & Firebase 构建。但它不是免费的。 codecanyon.net/item/country-picker-ios/25414188 【参考方案1】:

一个超级干净的 Swift 3 版本应该是:

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

您可以将语言环境标识符更改为例如。如果您想要本地化名称,则为 Locale.current.identifier。上面的示例仅适用于英语。

【讨论】:

到目前为止,这是 Swift 3 及更高版本的最佳答案。虽然?? nil 毫无意义。 在 Swift 5.1 上完美运行【参考方案2】:

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

【讨论】:

在 Swift 3 中不需要使用NSLocale @rmaddy - 然后发布一个不依赖 NSLocale 的替代方案。 @RobertGummesson 查看丹尼尔的答案。 @rmaddy - 对,错过了那个。 ...我同意你关于 nil 的评论。【参考方案3】:

尝试做这样的事情:

// 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 发现了这一点。

【讨论】:

这个答案肯定有效,但最重要的是 Swift 4.2 不再具有“sliceFrom”功能。而是像这样使用“replacingOccurrences”:theEnglishName.replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "")。 ***.com/a/53839473/4833705【参考方案4】:

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


【讨论】:

【参考方案5】:

试试这个

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

【讨论】:

【参考方案6】:

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

【讨论】:

不要在 Swift 3 中使用 NSLocale【参考方案7】:

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

【讨论】:

不要在 Swift 3 或 4 中使用 NSLocale。丹尼尔的回答显示了正确的解决方案,它在 Swift 4 中运行良好。【参考方案8】:

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

【讨论】:

真正的 Swift 3 答案将使用 Locale 而不是 NSLocale。 是的,我同意,但是,对于使用 NSLocale 的 IOS 8,如果您使用的是 Locale,则意味着 IOS 8 不会返回正确的响应。

以上是关于从国家代码中获取国家名称的主要内容,如果未能解决你的问题,请参考以下文章

从 Symfony2/Twig 中的 2 位国家代码获取翻译的国家名称?

从ios中的facebook登录获取国家名称和时区

需要从 open api 获取国家名称

如何使用国家代码或国家名称获取国家拨号代码?

如何从纬度和经度获取国家名称

使用 pycountry 从国家/地区获取大陆名称