从国家代码获取国家名称

25

我已经找到了使用Objective-C实现该功能的答案,但在Swift中实现有些困难。

我曾使用以下代码来获取当前位置的国家码:

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

但是我该如何将这个国家代码转换为国家名称呢?比如将“US”转换为“美国”的示例。


你可以查看 https://github.com/funky-monkey/IsoCountryCodes。 - olyv
你可以使用这个。它是一个由Swift和Firebase构建的完整模块。但它不是免费的。https://codecanyon.net/item/country-picker-ios/25414188 - Tulon
9个回答

49

一个超级干净的 Swift 3 版本会是这样的:

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

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


1
到目前为止,这绝对是Swift 3及更高版本的最佳答案。尽管?? nil是多余的。 - rmaddy
在 Swift 5.1 上完美运行。 - LondonGuy
或者你可以直接使用Locale.current.localizedString(forRegionCode: countryCode) - undefined

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

在 Swift 3 中不需要使用 NSLocale - rmaddy
@rmaddy - 那么请发布一份无需 NSLocale 依赖的替代方案。 - Robert Gummesson
2
@RobertGummesson 请看Daniel的回答。 - rmaddy
@rmaddy - 对,我漏掉了那个。...而且我同意你关于nil的评论。 - Robert Gummesson

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

我通过研究这个相关问题找到了答案。


这个答案肯定是可行的,但是在Swift 4.2的顶部部分不再有“sliceFrom”函数。相反,使用'replacingOccurrences',像这样:theEnglishName.replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "")。https://dev59.com/94_is4cB2Jgan1zn_2n6#53839473 - Lance Samaria

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

}

1
如果您想要打印国家名称和国旗,这是代码。
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

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

不要在Swift 3或4中使用NSLocale。Daniel的答案显示了正确的解决方案,并且在Swift 4中可以正常工作。 - rmaddy

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

不要在Swift 3中使用NSLocale - rmaddy

-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没有列出所有国家名称(例如:"en_US")。

2
一个真正的Swift 3答案将使用Locale而不是NSLocale。 - Eric Aya
是的,我同意。但是,对于IOS 8,我正在使用NSLocale,如果您使用的是Locale,则IOS 8无法返回正确的响应。 - Kalidoss Shanmugam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接