【问题标题】:Get country code from country name in IOS从IOS中的国家名称获取国家代码
【发布时间】:2012-10-01 10:48:30
【问题描述】:

我正在从服务器检索一个英文国家名称。例如,“西班牙”

我想做的是,假设国家名称要用英文写,得到国家代码。

我该怎么办?我发现从国家代码中获取国家名称非常容易,但我不知道如何进行相反的操作。

非常感谢。

【问题讨论】:

  • 您是如何从国家名称中获取代码的?反其道而行之:)
  • 希望这个链接能帮到你stackoverflow.com/questions/502764/…
  • 我已经检查过了,但我想要的是根据国家名称获取一个 CountryCode,而不是国家列表

标签: ios country-codes nslocale


【解决方案1】:

Jef 的 answer 在这里提供了帮助,并略有补充。

NSArray *countryCodes = [NSLocale ISOCountryCodes];
NSMutableArray *countries = [NSMutableArray arrayWithCapacity:[countryCodes count]];

for (NSString *countryCode in countryCodes)
{
    NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]];
    NSString *country = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_UK"] displayNameForKey: NSLocaleIdentifier value: identifier];
    [countries addObject: country];
}

NSDictionary *codeForCountryDictionary = [[NSDictionary alloc] initWithObjects:countryCodes forKeys:countries];

现在浏览“codeForCountryDictionary”,其中包含您需要代码的国家/地区名称,例如,

NSLog(@"%@",[codeForCountryDictionary objectForKey:@"Spain"]);

将产生结果为“ES”,这是西班牙的 2 个字母国家/地区代码。

【讨论】:

  • 好吧,如果您知道国家名称是英文的,那么您当然不应该使用 currentLocale,而是使用固定的语言环境。 currentLocale 可以是任何语言。请改用 [NSLocale initWithLocaleIdentifier:@"en_UK"]。
  • initWithLocaleIdentifier 是实例方法,不是类方法,所以请改用[[NSLocale alloc] initWithLocaleIdentifier:@"en_UK"]
  • 只是为了确保我也会小写/大写字典键。我们不确定服务器返回什么(这是一个不同的问题,但至少可以最大限度地减少“displayName”的弱点)
【解决方案2】:

Swift 4 更新版本的@Daxesh Nagar 解决方案:

private func locale(for fullCountryName : String) -> String {
    var locales : String = ""
    for localeCode in NSLocale.isoCountryCodes {
        let identifier = NSLocale(localeIdentifier: localeCode)
        let countryName = identifier.displayName(forKey: NSLocale.Key.countryCode, value: localeCode)
        if fullCountryName.lowercased() == countryName?.lowercased() {
            return localeCode as! String
        }
    }
    return locales
}

为此输入为 fullCountryName

“英国”

它将返回国家代码如下

“国标”

希望对大家有帮助!

【讨论】:

  • 这似乎只有在您使用英语语言环境时才有效,对吧?如果fullCountryName 是“Estados Unidos”,有什么建议吗?很好的解决方案,谢谢!
  • 我会为这个函数建议一个更好的名字。这不会返回语言环境,而是返回国家/地区代码。
  • 请注意,此代码仅在国家名称使用国家代码的适当语言时才有效。例如,“Spain”只给出“España”返回“ES”。
【解决方案3】:

在 Swift 中您将使用此代码

extension NSLocale {
    class func locales1(countryName1 : String) -> String {
        var locales : String = ""
        for localeCode in NSLocale.ISOCountryCodes() {
            let countryName = NSLocale.systemLocale().displayNameForKey(NSLocaleCountryCode, value: localeCode)!
            if countryName1.lowercaseString == countryName.lowercaseString {
                return localeCode as! String
            }
        }
        return locales
    }


}

获取数据:

strP2countrycode = NSLocale.locales1("PASS_COUNTRYNAME")

【讨论】:

    【解决方案4】:

    使用swift 3(上面的一些答案缺少一块)

    extension NSLocale {
    class func locales1(countryName1 : String) -> String {
        let locales : String = ""
        for localeCode in NSLocale.isoCountryCodes {
            let countryName = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: localeCode)
            if countryName1.lowercased() == countryName?.lowercased() {
                return localeCode
            }
        }
        return locales
    }
    }
    

    【讨论】:

    • 为什么要在 Swift 3 中创建 NSLocale 扩展而不是 Locale
    【解决方案5】:

    我的精简版包括仅匹配英文国家名称版本的修复。

    extension NSLocale
    {
        class func localeForCountry(countryName : String) -> String?
        {
            return NSLocale.ISOCountryCodes().first{self.countryNameFromLocaleCode($0 as! String) == countryName} as? String
        }
    
        private class func countryNameFromLocaleCode(localeCode : String) -> String
        {
            return NSLocale(localeIdentifier: "en_UK").displayNameForKey(NSLocaleCountryCode, value: localeCode) ?? ""
        }
    }
    

    【讨论】:

    • 如果您想确保标准的英文名称和格式,我建议您使用特殊的语言环境en_US_POSIX
    【解决方案6】:

    这是一个适用于 Swift 3 或更高版本的简单解决方案。根据您的操作系统版本,这支持大约 256 个国家/地区名称和代码。

    extension Locale {
        func isoCode(for countryName: String) -> String? {
            return Locale.isoRegionCodes.first(where: { (code) -> Bool in
                localizedString(forRegionCode: code)?.compare(countryName, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame
            })
        }
    }
    

    正确使用此方法的诀窍是了解您希望转换为标准 2 字母 ISO 国家/地区代码的国家/地区名称的语言。

    如果您知道国家/地区名称是英文的,则必须在设置为英文的语言环境中使用它。在这种情况下,最好使用 en_US_POSIX 的特殊语言环境。

    let locale = Locale(identifier: "en_US_POSIX") 
    print(locale.isoCode(for: "Spain")) // result is `ES`
    

    如果您有西班牙文的国家/地区名称,请务必使用西班牙语言环境:

    let locale = Locale(identifier: "es") 
    print(locale.isoCode(for: "España")) // result is `ES`
    

    【讨论】:

      【解决方案7】:

      Swift 3.0:

      获取国家代码和国家名称作为 NS 字典-

      let countryCodes: [AnyObject] = NSLocale.isoCountryCodes as [AnyObject]
      
              let countries: NSMutableArray = NSMutableArray(capacity: countryCodes.count)
      
              for countryCode in countryCodes {
                  let identifier: String = NSLocale.localeIdentifier(fromComponents: NSDictionary(object: countryCode, forKey: NSLocale.Key.countryCode as NSCopying) as! [String : String])
                  let country: String = NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: identifier)!
                  countries.add(country)
              }
              let codeForCountryDictionary: [NSObject : AnyObject] = NSDictionary(objects: countryCodes, forKeys: countries as! [NSCopying]) as [NSObject : AnyObject]
      
              print(codeForCountryDictionary)
      

      【讨论】:

      • 为什么 Swift 3 中的所有 NS 类?
      【解决方案8】:

      所以这个解决方案在 swift 4 中运行良好,取自上面的 cmets...

      extension NSLocale {
         struct Locale {
          let countryCode: String
          let countryName: String
         }
      
        class func locales() -> [Locale] {
      
          var locales = [Locale]()
      
          for localeCode in NSLocale.isoCountryCodes {
              let identifier = NSLocale(localeIdentifier: localeCode)
              let countryName = identifier.displayName(forKey: NSLocale.Key.countryCode, value: localeCode)!
              let countryCode = localeCode
              let locale = Locale(countryCode: countryCode, countryName: countryName)
              locales.append(locale)
          }
      
          return locales.sorted{$0.countryName.localizedCaseInsensitiveCompare($1.countryName) == ComparisonResult.orderedAscending}
       }
      }
      

      享受吧!

      【讨论】:

      • 这不会试图回答这个问题。而且你当然不应该在 Swift 中命名结构 Locale,因为 Locale 已经是 Foundation 提供的结构。
      【解决方案9】:

      斯威夫特 5

      extension Locale {
          func countryCode(by countryName: String) -> String? {
              return Locale.isoRegionCodes.first(where: { code -> Bool in
                  guard let localizedCountryName = localizedString(forRegionCode: code) else {
                      return false
                  }
                  return localizedCountryName.lowercased() == countryName.lowercased()
              })
          }
      }
      

      使用方法:

      let locale = Locale(identifier: "en_US")
      let countryCode = locale.countryCode(by: "Russia")
      

      【讨论】:

        猜你喜欢
        • 2016-06-11
        • 1970-01-01
        • 1970-01-01
        • 2016-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-13
        相关资源
        最近更新 更多