NSLocale语言问题

Sim*_*iwi 7 locale ios nslocale

所以在我的应用程序中,我试图让设备目前设置语言及其首字母缩略词.所以我这样做:

NSString *fullLanguage = [[NSLocale currentLocale] displayNameForKey:NSLocaleIdentifier value:[[NSLocale preferredLanguages] objectAtIndex:0]];
NSString *abrlanguage = [[NSLocale preferredLanguages] objectAtIndex:0];
Run Code Online (Sandbox Code Playgroud)

但是有些用户报告说语言正在返回类似:en_UK或类似的内容,这反过来又搞乱了我的应用程序的功能.

无论如何,有没有办法获得设备的当前设置语言,无论设备区域设置如何?

谢谢!

lna*_*ger 22

要获取语言代码,请使用:

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

要获取该语言的全名:

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

请注意,您使用的是区域代码(提供语言的区域变体),并且可以更容易地像这样:

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

区域代码以语言代码开头,后跟下划线,然后是区域变体.(这是根据Apple的文档标准化的.)

此外,如果您使用currentLocale,请知道它未更新,因为用户首选项已更改.使用autoupdatingCurrentLocale,如果你想保持同步,如果他们改变来代替.