Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLocale Language Issue

So in my app I am trying to get the devices currently set language and its acronym. So I do this:

NSString *fullLanguage = [[NSLocale currentLocale] displayNameForKey:NSLocaleIdentifier value:[[NSLocale preferredLanguages] objectAtIndex:0]];
NSString *abrlanguage = [[NSLocale preferredLanguages] objectAtIndex:0];

However some users report that the language is returning something like: en_UK or something similar, which in turn is messing up the functionality of my app.

Anyway is there a way to get the currently set language of the device regardless if the devices regional settings?

Thanks!

like image 238
SimplyKiwi Avatar asked Dec 16 '12 07:12

SimplyKiwi


People also ask

What is NSLocale?

An object representing information about linguistic, cultural, and technological conventions that bridges to Locale ; use NSLocale when you need reference semantics or other Foundation-specific behavior.

What is Currentlocale?

A locale representing the user's region settings at the time the property is read.


1 Answers

To get the language code, use:

NSString *languageCode = [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode];
NSLog(@"%@", languageCode);  // Prints "en"

To get the full name of the language:

NSString *languageName = [[NSLocale currentLocale] displayNameForKey:NSLocaleIdentifier value:languageCode];
NSLog(@"%@", languageName);  // Prints "English"

Note that you were using the region code (which provides for regional variations of languages), and could be gotten easier like this:

NSString *regionCode = [[NSLocale currentLocale] objectForKey:NSLocaleIdentifier];
NSLog(@"%@", regionCode);  // Prints "en_US"

Region codes start with the language code, followed by the underscore, and then the regional variation. (This is standardized per Apple's documentation.)

Also, if you use currentLocale, know that it is not updated as the users preferences are changed. Use autoupdatingCurrentLocale instead if you want to keep it in sync if they change.

like image 56
lnafziger Avatar answered Sep 28 '22 03:09

lnafziger