I have a menu that let's a user select a country. Exactly like that in the contacts.app country menu within the address field.
Does anyone know a simple way of getting a list of countries? I have used NSLocale to generate an array of countries but it's only the country codes unfortunately and not the human readable equivalent. I don't want 'GB' I want Great Britain.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
NSLocale *currentLocale = [NSLocale currentLocale]; // get the current locale. NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode]; // get country code, e.g. ES (Spain), FR (France), etc. If you want to find the country code of the current timezone, see @chings228's answer.
NSArray is an immutable Objective C class, therefore it is a reference type in Swift and it is bridged to Array<AnyObject> . NSMutableArray is the mutable subclass of NSArray .
Thanks chuck.
If anyone is interested or wanted to find the same solution here is my code for a sorted array of countries.
Objective-C:
NSLocale *locale = [NSLocale currentLocale]; NSArray *countryArray = [NSLocale ISOCountryCodes]; NSMutableArray *sortedCountryArray = [[NSMutableArray alloc] init]; for (NSString *countryCode in countryArray) { NSString *displayNameString = [locale displayNameForKey:NSLocaleCountryCode value:countryCode]; [sortedCountryArray addObject:displayNameString]; } [sortedCountryArray sortUsingSelector:@selector(localizedCompare:)];
Swift:
let locale = NSLocale.currentLocale() let countryArray = NSLocale.ISOCountryCodes() var unsortedCountryArray:[String] = [] for countryCode in countryArray { let displayNameString = locale.displayNameForKey(NSLocaleCountryCode, value: countryCode) if displayNameString != nil { unsortedCountryArray.append(displayNameString!) } } let sortedCountryArray = sorted(unsortedCountryArray, <)
Swift 3
let locale = NSLocale.current let unsortedCountries = NSLocale.isoCountryCodes.map { locale.localizedString(forRegionCode: $0)! } let sortedCountries = unsortedCountries.sorted()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With