从IOS的国家/地区名称获取国家/地区代码 [英] Get country code from country name in IOS

查看:3949
本文介绍了从IOS的国家/地区名称获取国家/地区代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用英语从服务器检索国家/地区名称。例如,西班牙

Im retrieving a country name from a server in english. For example, "Spain"

我想要做的是,假设国家名称将以英文书写,请获取国家/地区代码。

What I want to do is, assuming the country name is going to be written in english, get the country code.

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

What should I do? I´ve found getting the country name from the country code quite easy, but I´ve got no idea of how to do the opposite operation.

非常感谢。

推荐答案

杰夫的答案在这里有所帮助,只需稍加补充。

Jef's answer helped here, with slight additions.

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',其中包含您需要代码的国家/地区的名称,例如,

Now go through the 'codeForCountryDictionary' with the name of the country for which you require the code, for example,

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

将结果显示为'ES',这是西班牙的2个字母的国家代码。

would yield the result as 'ES', which is the 2 letter country code for spain.

这篇关于从IOS的国家/地区名称获取国家/地区代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆