Reputation: 333
I need to convert a list of country codes to a country array. Here is what I have done so far.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
pickerViewArray = [[NSMutableArray alloc] init]; //pickerViewArray is of type NSArray;
pickerViewArray =[NSLocale ISOCountryCodes];
}
Upvotes: 28
Views: 22361
Reputation: 19853
In Swift 3 the Foundation overlay changed quite a bit.
let countryName = Locale.current.localizedString(forRegionCode: countryCode)
If you would like country names in different languages you can specify the desired locale:
let locale = Locale(identifier: "es_ES") // Country names in Spanish
let countryName = locale.localizedString(forRegionCode: countryCode)
Upvotes: 24
Reputation: 4315
In iOS 9 and above you can retrieve the country name from the country code by doing:
NSString *countryName = [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:countryCode];
Where countryCode
is obviously the country code. (e.g: "US")
Upvotes: 6
Reputation: 7439
This will work in iOS8 :
NSArray *countryCodes = [NSLocale ISOCountryCodes];
NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:[countryCodes count]];
for (NSString *countryCode in countryCodes)
{
NSString *country = [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:countryCode];
[tmp addObject: country];
}
Upvotes: 25
Reputation: 2134
You can get an identifier for a country code with localeIdentifierFromComponents:
and then get its displayName
.
So to create an array with country names you can do:
NSMutableArray *countries = [NSMutableArray arrayWithCapacity: [[NSLocale ISOCountryCodes] count]];
for (NSString *countryCode in [NSLocale ISOCountryCodes])
{
NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]];
NSString *country = [[NSLocale currentLocale] displayNameForKey: NSLocaleIdentifier value: identifier];
[countries addObject: country];
}
To sort it alphabetically you can add
NSArray *sortedCountries = [countries sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Note that the sorted array is immutable.
Upvotes: 57