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个字母的国家代码.
小智 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
"英国"
它将返回国家/地区代码,如下所示
"国标"
希望它可以帮助你们!
| 归档时间: |
|
| 查看次数: |
27115 次 |
| 最近记录: |