【问题标题】:How do I get a list of countries in Swift ios?如何在 Swift ios 中获取国家/地区列表?
【发布时间】:2015-03-08 15:41:09
【问题描述】:

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

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

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

【问题讨论】:

标签: cocoa-touch swift nsarray uipickerview nslocale


【解决方案1】:

您可以使用 NSLocale 类的 isoCountryCodes 获取国家/地区列表,该类返回 [String] 数组。从那里,您可以使用NSLocaledisplayName(forKey:) 方法获取国家/地区名称。它看起来像这样:

var countries: [String] = []

for code in NSLocale.isoCountryCodes  {
    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)

【讨论】:

  • HIi 我可以获取所有州和城市,还可以像特定国家/地区一样过滤所有州和城市。谢谢
【解决方案2】:

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)

【讨论】:

    【解决方案3】:

    Swift 4.2

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

    【讨论】:

      【解决方案4】:

      Swift您可以轻松检索国家名称和国旗表情符号。

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

      结果

      【讨论】:

        【解决方案5】:

        和伊恩一样,但更短

        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)
        

        【讨论】:

          【解决方案6】:

          本地化显示的国家/地区名称也是一个好习惯。因此,除了 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)"
              }
          

          【讨论】:

          • 为什么人们会自动假设某人想看到的语言是“en_US”或“en_UK”或其他什么?我一直不明白为什么更多的人不按照你建议的方式去做。感谢您添加此内容!
          【解决方案7】:

          这是 @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)"
          }
          

          【讨论】:

            【解决方案8】:

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

            【讨论】:

            • 如果您对我投了反对票,请告诉我如何改进我的答案,谢谢
            【解决方案9】:

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

            【讨论】:

            • localizedString(forCountryCode: code) 仅适用于 iOS10
            【解决方案10】:

            更新到 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】:

              或者,您可以在 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
                }
              }
              

              【讨论】:

                【解决方案12】:

                这是 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]

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2014-08-10
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-10-04
                  • 1970-01-01
                  • 2013-02-27
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多