Detect language in use by iOS application

本小妞迷上赌 提交于 2019-12-02 02:42:00

问题


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.


回答1:


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).




回答2:


[[[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.)



来源:https://stackoverflow.com/questions/13966614/detect-language-in-use-by-ios-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!