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

k75qkfdt  于 2023-03-07  发布在  Swift
关注(0)|答案(9)|浏览(535)

我已经找到了目标c的答案,但我很难在swift中做到这一点。
我已使用此代码获取当前位置的国家代码:

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

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

bvjveswy

bvjveswy1#

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

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

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

fzwojiic

fzwojiic2#

雨燕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
    }
}
cczfrluj

cczfrluj3#

试着这样做:

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

pw136qt2

pw136qt24#

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

}
wh6knrhe

wh6knrhe5#

如果你想打印国家名称和国旗这里是代码

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
yb3bgrhw

yb3bgrhw6#

试试这个

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

cygmwpex7#

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

3okqufwl8#

雨燕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")
vtwuwzda

vtwuwzda9#

    • 雨燕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_美国")

相关问题