我正在从服务器上检索英文的国家名称。例如,“西班牙”
我想做的是,假设国家/地区名称将用英语书写,获取国家/地区代码。
我该怎么办?我发现从国家代码中获取国家名称非常容易,但我不知道如何做相反的操作。
非常感谢。
发布于 2012-11-30 17:39:51
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个字母的国家/地区代码。
发布于 2018-02-14 23:28:51
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
“英国”
它将返回国家代码,如下所示
"GB“
希望对你们有帮助!
发布于 2015-08-19 18:59:16
在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")https://stackoverflow.com/questions/12671829
复制相似问题