Converting Country Codes to Country Names
Asked Answered
A

4

28

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];
}
Administer answered 11/11, 2011 at 17:41 Comment(1)
Sorry , it is of type NSMutableArray;Administer
C
57

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.

Countercheck answered 11/11, 2011 at 17:57 Comment(4)
Thanks but the list is not Sorted ! how to do that ?Administer
I edited my answer assuming you want to sort it alphabetically.Countercheck
In iOS8 country is nil.Evenfall
That is returning the country language name. I would like to get the country nameFin
D
25

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];  
}
Danielldaniella answered 30/10, 2014 at 3:28 Comment(0)
A
24

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)
Anjanetteanjela answered 28/7, 2016 at 12:11 Comment(0)
A
6

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")

Agribusiness answered 24/3, 2016 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.