iOS: How to Get the Device Current Language Setting?

夙愿已清 提交于 2019-12-02 19:16:55

User preferred languages are stored can be retrieved from locale as array and current language identifier is the first object in that array:

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

If you want language in more readable form then use displayNameForKey:value: method of NSLocale:

NSString *langID = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *lang = [[NSLocale currentLocale] displayNameForKey:NSLocaleLanguageCode value:langID];

Try this:

NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSArray* arrayLanguages = [userDefaults objectForKey:@"AppleLanguages"];
NSString* currentLanguage = [arrayLanguages objectAtIndex:0];

Getting language and region in Swift:

    LF.log("language", NSLocale.preferredLanguages())
    LF.log("locale", NSBundle.mainBundle().preferredLocalizations)

In my case I'm getting:

language: '(
    "zh-Hans"
)'
locale: '(
    en
)'

Swift:

let language = NSBundle.mainBundle().preferredLocalizations[0] as NSString

Working solution:

    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)
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0]; 

Find the solution in XCode's helper document, it wrote:

Getting the Current Language

To get the language that the app is using from the main application bundle, use the preferredLocalizations method in the NSBundle class:

NSString *languageID = [[NSBundle mainBundle] preferredLocalizations].firstObject;

In Swift 4:

let currentLanguage = Locale.current.languageCode

It will give you just the language code, no country code.

Use below code to fetch Localised language without having trouble to the en-india, en-us etc..

 NSString *Ph = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];

In and After ios9 this code need to take in cosideration

To know the current language selected within your localizations use

[[NSBundle mainBundle] preferredLocalizations]

Example:

NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];

To get two letter word

NSString *language = [[[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0] substringToIndex:2];

Swift:

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