Get country code from country name in IOS
A Swift 4 updated version of @Daxesh Nagar solution:
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
}
For this Input as fullCountryName
"United Kingdom"
It will return the country code as follows
"GB"
Hope it helps you guys!
Jef's answer helped here, with slight additions.
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];
Now go through the 'codeForCountryDictionary' with the name of the country for which you require the code, for example,
NSLog(@"%@",[codeForCountryDictionary objectForKey:@"Spain"]);
would yield the result as 'ES', which is the 2 letter country code for spain.
In the Swift you will use this code
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
}
}
Get the data:
strP2countrycode = NSLocale.locales1("PASS_COUNTRYNAME")