I need to get a string like en_US
or es_ES
in iOS.
The obvious method is to use [NSLocale currentLocale]
and get the language info from there. However, that gives you the "region format" and not the actual device language, which means that if you have the device language in english but the region format as "spain", it'll erroneously report es_ES
.
If you need the device language you must do this instead:
[[NSLocale preferredLanguages] objectAtIndex:0]
However, that only gives you the language, so you get something like en
or es
, without the country code at the end.
How would I get the country code correctly, like Safari does?
Try with this code:
NSString *locale = [[NSLocale currentLocale] localeIdentifier];
NSRange startRange = [locale rangeOfString:@"_"];
NSString *result = [locale stringByReplacingCharactersInRange:NSMakeRange(0, startRange.length+1) withString:[[NSLocale preferredLanguages] objectAtIndex:0]];
DebugLog(@"current locale: %@", result);