如何获得Swift ios中的国家/地区列表?

时间:2015-01-10 11:00:33

标签: cocoa-touch swift nsarray uipickerview nslocale

我已经看过两个与我相似的问题,但这些问题的答案对我不起作用。我有一个旧项目,其中包含在一组方括号内手动输入的国家/地区列表。

我可以在我的pickerView中轻松使用它,但我想知道是否有更有效的方法来做到这一点?

我将使用UIPickerView中的国家/地区列表。

12 个答案:

答案 0 :(得分:28)

您可以使用NSLocale类ISOCountryCodes()方法获取国家/地区列表,该方法会返回[AnyObject]数组,并将其转换为[String]。从那里,您可以使用NSLocale的displayNameForKey方法获取国家/地区名称。它看起来像这样:

var countries: [String] = []

for code in NSLocale.ISOCountryCodes() as [String] {
    let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
    let name = NSLocale(localeIdentifier: "en_UK").displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)"
    countries.append(name)
    }

println(countries)

答案 1 :(得分:15)

SWIFT 3和4

var countries: [String] = []

for code in NSLocale.isoCountryCodes as [String] {
    let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
    let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
    countries.append(name)
}

print(countries)

答案 2 :(得分:7)

与Ian相同但更短

let countries = NSLocale.ISOCountryCodes().map { (code:String) -> String in
  let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
  return NSLocale(localeIdentifier: "en_US").displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)"
}

print(countries)

答案 3 :(得分:5)

快速,您可以轻松检索国家名称及其标志表情符号。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var countriesData = [(name: String, flag: String)]()

        for code in NSLocale.isoCountryCodes  {

            let flag = String.emojiFlag(for: code)
            let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])

            if let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) {
                countriesData.append((name: name, flag: flag!))
            }else{
                 //"Country not found for code: \(code)"
            }
        }

        print(countriesData)
    }
}


extension String {

    static func emojiFlag(for countryCode: String) -> String! {
        func isLowercaseASCIIScalar(_ scalar: Unicode.Scalar) -> Bool {
            return scalar.value >= 0x61 && scalar.value <= 0x7A
        }

        func regionalIndicatorSymbol(for scalar: Unicode.Scalar) -> Unicode.Scalar {
            precondition(isLowercaseASCIIScalar(scalar))

            // 0x1F1E6 marks the start of the Regional Indicator Symbol range and corresponds to 'A'
            // 0x61 marks the start of the lowercase ASCII alphabet: 'a'
            return Unicode.Scalar(scalar.value + (0x1F1E6 - 0x61))!
        }

        let lowercasedCode = countryCode.lowercased()
        guard lowercasedCode.count == 2 else { return nil }
        guard lowercasedCode.unicodeScalars.reduce(true, { accum, scalar in accum && isLowercaseASCIIScalar(scalar) }) else { return nil }

        let indicatorSymbols = lowercasedCode.unicodeScalars.map({ regionalIndicatorSymbol(for: $0) })
        return String(indicatorSymbols.map({ Character($0) }))
    }
}

结果

enter image description here

答案 4 :(得分:4)

这是@ vedo27在Swift 3中的回答

 let countries = NSLocale.isoCountryCodes.map { (code:String) -> String in
    let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
    return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}

答案 5 :(得分:2)

将本地显示的国家/地区名称本地化也是一种很好的做法。所以除了vedo27的回答,它将是:

let countriesArray = NSLocale.ISOCountryCodes().map { (code:String) -> String in
        let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
        let currentLocaleID = NSLocale.currentLocale().localeIdentifier
        return NSLocale(localeIdentifier: currentLocaleID).displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)"
    }

答案 6 :(得分:2)

Swift 3声明为var

var countries: [String] {
    let myLanguageId = "en" // in which language I want to show the list
    return NSLocale.isoCountryCodes.map {
        return NSLocale(localeIdentifier: myLanguageId).localizedString(forCountryCode: $0) ?? $0
    }
}

答案 7 :(得分:2)

SWIFT 4

这是在Swift 4中实现它的一种优雅方式

var countries: [String] = {

    var arrayOfCountries: [String] = []

    for code in NSLocale.isoCountryCodes as [String] {
        let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
        let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
        arrayOfCountries.append(name)
    }

    return arrayOfCountries
}()

答案 8 :(得分:1)

或者,您可以在swift 4中使用它并使用系统语言进行本地化。

import Foundation

struct Country {
  let name: String
  let code: String
}

final class CountryHelper {
  class func allCountries() -> [Country] {
    var countries = [Country]()

    for code in Locale.isoRegionCodes as [String] {
      if let name = Locale.autoupdatingCurrent.localizedString(forRegionCode: code) {
        countries.append(Country(name: name, code: code))
      }
    }

    return countries
  }
}

答案 9 :(得分:1)

Swift 4.2

let languageList = Locale.isoLanguageCodes.compactMap { Locale.current.localizedString(forLanguageCode: $0) }
let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }

答案 10 :(得分:1)

更新为vedo27的答案,但在 迅速5:

let countries : [String] = NSLocale.isoCountryCodes.map { (code:String) -> String in
        let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
        return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
    }

对于按字母顺序排列的国家/地区也要有一个排序的数组,请在获取国家/地区列表后按您的顺序在下方添加

let sortedcountries = countries.sorted { $0 < $1 }

答案 11 :(得分:0)

这是Swift 5.1的代码(至少对我来说是有效的,因为许多功能已重命名):

let array = NSLocale.isoCountryCodes.map
{
        (code:String) -> String in
        
        let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
        let currentLocaleID = NSLocale.current.identifier
        return NSLocale(localeIdentifier: currentLocaleID).displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}

这是一个[String]