Getting current device language in iOS?

2018-12-31 09:41发布

I'd like to show the current language that the device UI is using. What code would I use?

I want this as an NSString in fully spelled out format. (Not @"en_US")

EDIT: For those driving on by, there are a ton of useful comments here, as the answer has evolved with new iOS releases.

28条回答
不流泪的眼
2楼-- · 2018-12-31 10:27

In Swift:

let languageCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String
查看更多
栀子花@的思念
3楼-- · 2018-12-31 10:28

The selected answer returns the current device language, but not the actual language used in the app. If you don't provide a localization in your app for the user's preferred language, the first localization available, ordered by the user's preferred order, is used.

To discover the current language selected within your localizations use

[[NSBundle mainBundle] preferredLocalizations];

Example:

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

Swift:

let language = NSBundle.mainBundle().preferredLocalizations.first as NSString
查看更多
素衣白纱
4楼-- · 2018-12-31 10:28

I tried to found out the right solution for myself. When I use Locale.preferredLanguages.first was returned the preferred language from your app settings.

If you want get to know language from user device settings, you should the use string below:

Swift 3

let currentDeviceLanguage = Locale.current.languageCode
// Will return the optional String

To unwrap and use look at the line below:

if let currentDeviceLanguage = Locale.current.languageCode {
    print("currentLanguage", currentDeviceLanguage)

    // For example
    if currentDeviceLanguage == "he" {
        UIView.appearance().semanticContentAttribute = .forceRightToLeft
    } else {
        UIView.appearance().semanticContentAttribute = .forceLeftToRight
    }
}
查看更多
人间绝色
5楼-- · 2018-12-31 10:28

For Swift 3.0 below code can be used to answer your question:

 let language = Bundle.main.preferredLocalizations.first! as NSString
查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 10:29

According to Apple documentation

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];
查看更多
看风景的人
7楼-- · 2018-12-31 10:30

For getting user device current language use the following it code it worked for me.

NSString * myString = [[NSLocale preferredlanguage]objectAtIndex:0];
查看更多
登录 后发表回答