且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在iOS中获取当前的设备语言?

更新时间:2022-06-18 02:36:44

提供的解决方案实际上会返回设备的当前区域,而不是当前选择的语言。这些通常是一样的。然而,如果我在北美,我把我的语言设置为日语,我的地区仍将是英语(美国)。为了检索当前选择的语言,您可以:

The solutions provided will actually return the current region of the device - not the currently selected language. These are often one and the same. However, if I am in North America and I set my language to Japanese, my region will still be English (United States). In order to retrieve the currently selected language, you can do:

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

这将返回当前所选语言的双字母代码。 en代表英语,es代表西班牙语,de代表德语,等等。更多示例请参见此***条目(特别是639-1列):

This will return a two letter code for the currently selected language. "en" for English, "es" for Spanish, "de" for German, etc. For more examples, please see this Wikipedia entry (in particular, the 639-1 column):

ISO 639-1代码列表

这是一个简单的事情,将两个字母的代码转换为你想显示的字符串。所以如果是en,显示英语。

Then it's a simple matter of converting the two letter codes to the string you would like to display. So if it's "en", display "English".

希望这有助于有人区分区域和当前选择的语言。

Hope this helps someone that's looking to differentiate between region and currently selected language.

EDIT

值得引用NSLocale.h的标题信息:

Worth to quote the header information from NSLocale.h:

+ (NSArray *)preferredLanguages NS_AVAILABLE(10_5, 2_0); // note that this list does not indicate what language the app is actually running in; the [NSBundle mainBundle] object determines that at launch and knows that information

请查看 @ mindvision的回答