Question

How can I detect the current application language ? I am not talking about NSLocale user preferences.

In my app there are currently two supported languages. A default 'en' and a specific 'it'.

I just wanted to know which one is actually in use. If it is relevant, as a further explanation, I am providing content trough a web service only for the two supported languages. When invoking the service I need to pass a language parameter. Currently I am doing this, it works, but I totally dislike it:

NSString *preferredLanguage = [[NSLocale preferredLanguages] objectAtIndex:0];

if (![preferredLanguage isEqualToString:@"it"] && ![preferredLanguage isEqualToString:@"en"]) {
    return @"en";
}
return preferredLanguage;

I have looked trough the NSLocale class and UIApplication, but didn't manage to find anything useful.

I also notice that NSBundle has some localization methods, but they all seems not specific about which one is in use.

Was it helpful?

Solution 2

I usually reserve a special key in Localizable.strings, such as "HTTPAcceptLanguage", which I set to "en", "fr", etc. Now telling your server the language displayed by the application is as simple as NSLocalizedString(@"HTTPAcceptLanguage", nil).

OTHER TIPS

[[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0] would be better, because it will always return a localization that your app supports. There is no need for an additional check afterwards.

In fact, your code has a bug. If the first language in the user's preferences is not one that your app supports, iOS will continue down the list until it finds one that your app does support. So if the user's preferences were "fr", "it", "en", ..., iOS would load the it versions of your resources. However, your code would fall back to en.

(This is perhaps more important on OS X, where it's easy for the user to change the language ordering. On iOS it's apparently possible to do that, but it's not as obvious how it works.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top