我的应用程序中有一些功能应该基于运行它的设备的语言设置。
我想获得实际语言,而不是某些国家/地区设置。例如,如果语言是英语,我不在乎它是美国,英国,澳大利亚等......
我熟悉NSLocale
对象,但它似乎与Region Format
设置有关,而与语言设置有关(请参见下面的屏幕截图),所以当我尝试使用[locale displayNameForKey:NSLocaleIdentifier value:[locale localeIdentifier]
从中检索语言。我得到的内容是English (United States)
而不是English
;另外,我认为我需要的是语言数据,而不是地区格式(我是对的吗?)。
有人可以指导我如何检索语言设置吗?
答案 0 :(得分:51)
存储的用户首选语言可以从区域设置中检索为数组,当前语言标识符是该数组中的第一个对象:
NSString *currentLanguage = [[NSLocale preferredLanguages] objectAtIndex:0];
如果您想要更易读的语言,请使用NSLocale的displayNameForKey:value:
方法:
NSString *langID = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *lang = [[NSLocale currentLocale] displayNameForKey:NSLocaleLanguageCode value:langID];
答案 1 :(得分:5)
试试这个:
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSArray* arrayLanguages = [userDefaults objectForKey:@"AppleLanguages"];
NSString* currentLanguage = [arrayLanguages objectAtIndex:0];
答案 2 :(得分:3)
在Swift
中获取语言和区域:
LF.log("language", NSLocale.preferredLanguages())
LF.log("locale", NSBundle.mainBundle().preferredLocalizations)
就我而言,我得到了:
language: '(
"zh-Hans"
)'
locale: '(
en
)'
答案 3 :(得分:2)
夫特:
let language = NSBundle.mainBundle().preferredLocalizations[0] as NSString
答案 4 :(得分:2)
工作解决方案:
let language = NSLocale.preferredLanguages()[0]
let languageDic = NSLocale.componentsFromLocaleIdentifier(language) as NSDictionary
//let countryCode = languageDic.objectForKey("kCFLocaleCountryCodeKey")
let languageCode = languageDic.objectForKey("kCFLocaleLanguageCodeKey") as! String
print(languageCode)
答案 5 :(得分:1)
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
答案 6 :(得分:1)
在XCode的帮助文档中找到解决方案,它写道:
获取当前语言
要从主应用程序包中获取应用程序正在使用的语言,请使用NSBundle类中的preferredLocalizations方法:
NSString *languageID = [[NSBundle mainBundle] preferredLocalizations].firstObject;
答案 7 :(得分:1)
在 Swift 4 中:
let currentLanguage = Locale.current.languageCode
它只会给您语言代码,而没有国家代码。
答案 8 :(得分:0)
使用以下代码获取本地化语言,而不会给en-india,en-us等带来麻烦。
NSString *Ph = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
在ios9中和之后,这段代码需要考虑到这个问题
答案 9 :(得分:-1)
要了解您在本地化中选择的当前语言,请使用
[[NSBundle mainBundle] preferredLocalizations]
示例:
NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
获得两个字母的单词
NSString *language = [[[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0] substringToIndex:2];
夫特:
let language = NSBundle.mainBundle().preferredLocalizations.first as NSString