从IOS中的国家/地区名称获取国家/地区代

pdr*_*rod 22 country-codes ios nslocale

我用英语从服务器检索国家名称.例如,"西班牙"

我想要做的是,假设国家名称将用英文写,请获取国家代码.

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

非常感谢.

Bre*_*int 30

杰夫的回答在这里有所帮助,略有补充.

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];
Run Code Online (Sandbox Code Playgroud)

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

NSLog(@"%@",[codeForCountryDictionary objectForKey:@"Spain"]);
Run Code Online (Sandbox Code Playgroud)

将结果产生为'ES',这是西班牙的2个字母的国家代码.

  • 好吧,如果你知道国家名称是英文的,你当然不应该使用currentLocale,而是使用固定的语言环境.currentLocale可以使用任何语言.请改用[NSLocale initWithLocaleIdentifier:@"en_UK"]. (4认同)

小智 6

一个斯威夫特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
}
Run Code Online (Sandbox Code Playgroud)

对于此输入为fullCountryName

"英国"

它将返回国家/地区代码,如下所示

"国标"

希望它可以帮助你们!