If you like my tutorials, you will love my book . It is chockful of advanced programming techniques and the only comprehensive barcode reference for serious iOS developers.
Our DNA is written in Objective-C

Getting the User's Language

Geppy Parziale wrote about this topic on his “Invasive Code” blog. The method he proposes is to be found in Apple’s documentation and looks like this:

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];

This is a good method to retrieve the set language, BUT it has two major drawbacks when used in regular apps:

  • Changes are not visible to the app by simply changing the language in settings. It seems you also have to change the region for it to be effective.
  • This really returns the user’s set language but for most cases you instead want to know which localization is used.

What good does it get you if you know that the user has set Klingon as his iPhone language? Not much because most of the time you then still want to know which localization is the currently active one.

You know if the iPhone is set to any language that is not amongst your localizations then the auto-localization feature falls back to the app’s default language, usually English. If you add German localization and the user chooses German then this is automatically used.

I learned this the hard way when we added multiple languages to LuckyWheel. Now here’s the method that I found to be way more useful:

NSString *selectedLocale = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];

If you read Apple’s page to the end you get to a box where it says:

“Although you can get the user’s preferred settings from the defaults database, it is recommended you use the CFBundleRef functions or NSBundle class instead. The associated functions and methods of those objects return the preferred language or locale that is also supported by your application.”

That’s exactly what I am saying …

Categories: Recipes

%d bloggers like this: