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

时间:2021-08-30 07:27:23

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

我想要显示设备UI正在使用的当前语言。我将使用什么代码?

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

我想把这个作为NSString的完整格式。(@ 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.

编辑:对于那些开车的人来说,这里有很多有用的评论,因为答案随着新的iOS版本的发布而发展。

28 个解决方案

#1


760  

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] firstObject];

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):

这将返回当前所选语言的两个字母代码。“en”代表英语,“es”表示西班牙语,“de”表示德语,等等。更多的例子,请参见*词条(尤其是639-1栏):

List of ISO 639-1 codes

ISO 639-1代码清单。

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".

然后,将两个字母代码转换为您想要显示的字符串是一个简单的问题。所以如果是en,显示“English”。

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

希望这能帮助那些想要区分区域和当前选择语言的人。

EDIT

编辑

Worth to quote the header information from NSLocale.h:

引用来自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

People interested in app language take a look at @mindvision's answer

对应用语言感兴趣的人可以看看@mindvision的答案。

#2


258  

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

#3


73  

Solution for iOS 9:

解决方案iOS 9:

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

language = "en-US"

语言=“en - us”

NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];

languageDic will have the needed components

languageDic将有所需的组件。

NSString *countryCode = [languageDic objectForKey:@"kCFLocaleCountryCodeKey"];

countryCode = "US"

countryCode = "我们"

NSString *languageCode = [languageDic objectForKey:@"kCFLocaleLanguageCodeKey"];

languageCode = "en"

languageCode = "恩"

#4


64  

This will probably give you what you want:

这可能会给你想要的东西:

NSLocale *locale = [NSLocale currentLocale];

NSString *language = [locale displayNameForKey:NSLocaleIdentifier 
                                         value:[locale localeIdentifier]];

It will show the name of the language, in the language itself. For example:

它将显示语言的名称,在语言本身中。例如:

Français (France)
English (United States)

#5


27  

在iOS中获取当前的设备语言? The accepted, and the other answers all don't take into account that the preferred language can be another language than the device language.

被接受的和其他的答案都没有考虑到首选语言可能是另一种语言而不是设备语言。

The device language is the language in which operating system elements and Apple apps are presented.

设备语言是操作系统元素和苹果应用程序的语言。

The preferred language is the language the user would like to have apps localized in. Apple only provides a limited set of translations. If the preferred language is one language Apple translated their apps to, it will also be the device language. However if the user prefers a language for which Apple doesn't provide translations the device and preferred languages won't match. The device language will not be on first position in the preferred languages list.

首选语言是用户希望应用程序本地化的语言。苹果只提供有限的翻译。如果首选语言是一种语言,苹果将其应用程序翻译为,它也将是设备语言。然而,如果用户喜欢一种苹果不提供翻译的语言,设备和首选语言就不会匹配。设备语言不会位于首选语言列表中的第一个位置。

The following function will go through the preferred languages list and check if there is a translation in the Apple frameworks. The first language to have a translation is the device language. The function will return its language code.

下面的函数将通过首选语言列表,并检查Apple框架是否有翻译。第一个有翻译的语言是设备语言。函数将返回其语言代码。

func deviceLanguage() -> String? {
    let systemBundle: NSBundle = NSBundle(forClass: UIView.self)
    let englishLocale: NSLocale = NSLocale(localeIdentifier: "en")

    let preferredLanguages: [String] = NSLocale.preferredLanguages()

    for language: String in preferredLanguages {
        let languageComponents: [String : String] = NSLocale.componentsFromLocaleIdentifier(language)

        guard let languageCode: String = languageComponents[NSLocaleLanguageCode] else {
            continue
        }

        // ex: es_MX.lproj, zh_CN.lproj
        if let countryCode: String = languageComponents[NSLocaleCountryCode] {
            if systemBundle.pathForResource("\(languageCode)_\(countryCode)", ofType: "lproj") != nil {
                // returns language and country code because it appears that the actual language is coded within the country code aswell
                // for example: zh_CN probably mandarin, zh_HK probably cantonese
                return language
            }
        }

        // ex: English.lproj, German.lproj
        if let languageName: String = englishLocale.displayNameForKey(NSLocaleIdentifier, value: languageCode) {
            if systemBundle.pathForResource(languageName, ofType: "lproj") != nil {
                return languageCode
            }
        }

        // ex: pt.lproj, hu.lproj
        if systemBundle.pathForResource(languageCode, ofType: "lproj") != nil {
            return languageCode
        }
    }

    return nil
}

This works if the preferred language list is:

如果首选语言列表是:

  1. Afrikaans (iOS is not translated into Afrikaans)
  2. 南非荷兰语(iOS没有翻译成南非荷兰语)
  3. Spanish (Device Language)
  4. 西班牙语语言(设备)

The preferred language list can be edited in: Settings.app -> General -> Language & Region -> Preferred Language Order

首选语言列表可以在:设置中进行编辑。app ->通用->语言&区域->首选语言顺序。


You can than use the device language code and translate it into the language name. The following lines will print the device language in the device language. For example "Español" if the device is set to spanish.

您可以使用设备语言代码并将其转换为语言名称。以下几行将在设备语言中打印设备语言。例如“Espanol”,如果设备设置为西班牙语。

if let deviceLanguageCode: String = deviceLanguage() {
    let printOutputLanguageCode: String = deviceLanguageCode
    let printOutputLocale: NSLocale = NSLocale(localeIdentifier: printOutputLanguageCode)

    if let deviceLanguageName: String = printOutputLocale.displayNameForKey(NSLocaleIdentifier, value: deviceLanguageCode) {
        // keep in mind that for some localizations this will print a language and a country
        // see deviceLanguage() implementation above
        print(deviceLanguageName)
    }
} 

#6


14  

i use this

我用这个

    NSArray *arr = [NSLocale preferredLanguages];
for (NSString *lan in arr) {
    NSLog(@"%@: %@ %@",lan, [NSLocale canonicalLanguageIdentifierFromString:lan], [[[NSLocale alloc] initWithLocaleIdentifier:lan] displayNameForKey:NSLocaleIdentifier value:lan]);
}

ignore memory leak..

忽略了内存泄漏。

and result is

和结果是

2013-03-02 20:01:57.457 xx[12334:907] zh-Hans: zh-Hans 中文(简体中文)
2013-03-02 20:01:57.460 xx[12334:907] en: en English
2013-03-02 20:01:57.462 xx[12334:907] ja: ja 日本語
2013-03-02 20:01:57.465 xx[12334:907] fr: fr français
2013-03-02 20:01:57.468 xx[12334:907] de: de Deutsch
2013-03-02 20:01:57.472 xx[12334:907] nl: nl Nederlands
2013-03-02 20:01:57.477 xx[12334:907] it: it italiano
2013-03-02 20:01:57.481 xx[12334:907] es: es español

#7


12  

Translating language codes such as en_US into English (United States) is a built in feature of NSLocale and NSLocale does not care where you get the language codes from. So there really is no reason to implement your own translation as the accepted answer suggests.

将en_US这样的语言代码翻译成英语(美国)是一种内置的NSLocale, NSLocale不关心你从哪里得到语言代码。因此,没有必要按照公认的答案来实现你自己的翻译。

// Example code - try changing the language codes and see what happens
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
NSString *l1 = [locale displayNameForKey:NSLocaleIdentifier value:@"en"];
NSString *l2 = [locale displayNameForKey:NSLocaleIdentifier value:@"de"];
NSString *l3 = [locale displayNameForKey:NSLocaleIdentifier value:@"sv"];
NSLog(@"%@, %@, %@", l1, l2, l3);

Prints: English, German, Swedish

打印:英语,德语,瑞典

#8


7  

You can use the displayNameForKey:value: method of NSLocale:

您可以使用displayNameForKey:value: NSLocale的方法:

// get a French locale instance
NSLocale *frLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease];

// use it to get translated display names of fr_FR and en_US
NSLog(@"%@", [frLocale displayNameForKey:NSLocaleIdentifier value:@"fr_FR"]);
NSLog(@"%@", [frLocale displayNameForKey:NSLocaleIdentifier value:@"en_US"]);

This will print out:

这将打印出:

français (France)
anglais (États-Unis)

If you specify the same locale identifier for the initWithLocaleIdentifier: and also the displayNameForKey:value: method, then it will give you the native name of the language. I've discovered that if you remove the country code and use just fr and en, that it will also omit the country from the display name (on Mac OS X at least, not sure about iOS).

如果您为initWithLocaleIdentifier指定了相同的区域标识符:以及displayNameForKey:value:方法,那么它将给您提供该语言的本机名称。我发现,如果你删除了国家代码,只使用fr和en,那么它也会从显示名(至少在Mac OS X上,不确定iOS)中省略这个国家。

#9


7  

Even there's a better way to get current device language. Let us try it by below code -

即使有更好的方法来获得当前的设备语言。让我们用下面的代码来试试。

NSLog(@"Current Language - %@", [[NSLocale preferredLanguages] firstObject]);

Suggested by Abizern on here

这里是Abizern建议的。

#10


5  

Swift

To get current language of device

获取设备的当前语言。

NSLocale.preferredLanguages()[0] as String

To get application language

让应用程序语言

NSBundle.mainBundle().preferredLocalizations[0] as NSString

Note:

注意:

It fetches the language that you have given in CFBundleDevelopmentRegion of info.plist

它会获取你在info.plist的CFBundleDevelopmentRegion中给出的语言。

if CFBundleAllowMixedLocalizations is true in info.plist then first item of CFBundleLocalizations in info.plist is returned

如果cfbundleallowmixedlocalize在info中是正确的。plist然后第一项cfbundleloc的信息。plist返回

#11


5  

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.

我试图找到适合自己的解决方案。当我使用Locale.preferredLanguages。首先从应用程序设置中返回首选语言。

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

如果你想从用户设备设置中了解语言,你应该使用下面的字符串:

Swift 3

斯威夫特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
    }
}

#12


4  

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

为了获得用户设备的当前语言,请使用以下代码为我工作。

NSString * myString = [[NSLocale preferredlanguage]objectAtIndex:0];

#13


3  

For MonoTouch C# developers use:

对于MonoTouch c#开发人员使用:

NSLocale.PreferredLanguages.FirstOrDefault() ?? "en"

Note: I know this was an iOS question, but as I am a MonoTouch developer, the answer on this page led me in the right direction and I thought I'd share the results.

注意:我知道这是一个iOS的问题,但由于我是一个MonoTouch开发人员,这个页面上的答案引导我找到了正确的方向,我想我应该分享一下结果。

#14


3  

Simple Swift 3 function:

简单的快速3函数:

  @discardableResult
  func getLanguageISO() -> String {
    let locale = Locale.current
    guard let languageCode = locale.languageCode,
          let regionCode = locale.regionCode else {
        return "de_DE"
    }
    return languageCode + "_" + regionCode
  }

#15


2  

-(NSString *)returnPreferredLanguage { //as written text

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSArray *preferredLanguages = [defaults objectForKey:@"AppleLanguages"];
NSString *preferredLanguageCode = [preferredLanguages objectAtIndex:0]; //preferred device language code
NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"]; //language name will be in English (or whatever)
NSString *languageName = [enLocale displayNameForKey:NSLocaleIdentifier value:preferredLanguageCode]; //name of language, eg. "French"
return languageName;

}

#16


2  

In Swift:

迅速:

let languageCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String

#17


2  

Swift 3

斯威夫特3

let locale = Locale.current
let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String?
print(code!)

#18


1  

If you want to get only language here is my suggested answer:

如果你想只得到语言,我建议的答案是:

NSString *langplusreg = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString * langonly = [[langplusreg componentsSeparatedByString:@"-"] 
objectAtIndex:0];

In my case i just wanted only Locale language not locale region.

在我的例子中,我只需要Locale语言而不是Locale区域。

Output: If your Locale language is Japanese and locale region is Japan then:

输出:如果您的地区语言是日本人,地区是日本:

langplusreg = ja-JP

langplusreg = ja-JP

langonly = ja

langone =是

#19


1  

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

对于Swift 3.0以下代码可以用来回答您的问题:

 let language = Bundle.main.preferredLocalizations.first! as NSString

#20


0  

According to Apple documentation

根据苹果公司的文档

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];

#21


0  

Two letters format. Apple uses the ISO standard ISO-3166.

两个字母的格式。苹果使用ISO标准ISO-3166。

NSString *localeCountryCode = [[NSLocale autoupdatingCurrentLocale] objectForKey:NSLocaleCountryCode];

#22


0  

@amir response in Swift :

@amir回应Swift:

// Get language prefered by user
    let langageRegion = NSLocale.preferredLanguages().first!
    let languageDic = NSLocale.componentsFromLocaleIdentifier(langageRegion)
    let language = languageDic[NSLocaleLanguageCode]

#23


0  

For Swift 3:

为迅速3:

NSLocale.preferredLanguages[0] as String

NSLocale。preferredLanguages[0]是字符串

#24


0  

As of iOS 9, if you just want the language code without country code, you'll want this sort of helper function - since the language will contain the country code.

在ios9中,如果您只想要没有国家代码的语言代码,您将需要这种帮助函数——因为语言将包含国家代码。

// gets the language code without country code in uppercase format, i.e. EN or DE
NSString* GetLanguageCode()
{
    static dispatch_once_t onceToken;
    static NSString* lang;
    dispatch_once(&onceToken, ^
    {
        lang = [[[NSLocale preferredLanguages] objectAtIndex:0] uppercaseString];
        NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"^[A-Za-z]+" options:0 error:nil];
        NSTextCheckingResult* match = [regex firstMatchInString:lang options:0 range:NSMakeRange(0, lang.length)];
        if (match.range.location != NSNotFound)
        {
            lang = [lang substringToIndex:match.range.length];
        }
    });
    return lang;
}

#25


0  

Obviously, the solutions relying, for example, on

显然,解决方案依赖于,例如,on。

[[NSLocale preferredLanguages] objectAtIndex:0]

usually work fine and return the current device language.

通常工作良好并返回当前设备语言。

But it could be misleading in some cases :

但在某些情况下可能会产生误导:

If the app in which you want to get this value has already changed the language, for example with this kind of code :

如果你想要得到这个值的应用程序已经改变了语言,例如使用这种代码:

NSString *lg = @"en"; // or anything like @"en", @"fr", etc.
[[NSUserDefaults standardUserDefaults] 
    setObject:[NSArray arrayWithObjects:lg, nil]  
    forKey:@"AppleLanguages"]

In this case, [NSLocale preferredLanguages] actually returns the preferred language set (and used) in this particular app, not the current device language !

在这种情况下,[NSLocale preferredLanguages]实际上会在这个特定的应用程序中返回首选语言集(和使用),而不是当前的设备语言!

And... in this case the only way to properly get the actual current device language (and not that previously set in the app), is to firstly clear the key @"appleLanguages" in NSUserDefaults, like this :

和…在这种情况下,正确获取实际当前设备语言(而不是之前在应用程序中设置的)的唯一方法是首先清除NSUserDefaults中的关键@“appleLanguages”,如下所示:

[[NSUserDefaults standardUserDefaults]removeObjectForKey:@"AppleLanguages"];

Then, [NSLocale preferredLanguages] now returns the correct value.

然后,[NSLocale preferredLanguages]现在返回正确的值。

Hope this help.

希望这个有帮助。

#26


0  

If you're looking for preferred language code ("en", "de", "es" ...), and localized preferred language name (for current locale), here's a simple extension in Swift:

如果您正在寻找首选语言代码(“en”、“de”、“es”…),以及本地化的首选语言名称(对于当前语言环境),下面是Swift的简单扩展:

extension Locale {
static var preferredLanguageIdentifier: String {
    let id = Locale.preferredLanguages.first!
    let comps = Locale.components(fromIdentifier: id)
    return comps.values.first!
}

static var preferredLanguageLocalizedString: String {
    let id = Locale.preferredLanguages.first!
    return Locale.current.localizedString(forLanguageCode: id)!
}

}

}

#27


0  

SWIFT-4

SWIFT-4

 // To get device default selected language. It will print like short name of zone. For english, en or spain, es.



let language = Bundle.main.preferredLocalizations.first! as NSString
    print("device language",language)

#28


0  

Updated answer for Swift 4

更新快4的答案。

let language = Bundle.main.preferredLocalizations.first

#1


760  

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] firstObject];

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):

这将返回当前所选语言的两个字母代码。“en”代表英语,“es”表示西班牙语,“de”表示德语,等等。更多的例子,请参见*词条(尤其是639-1栏):

List of ISO 639-1 codes

ISO 639-1代码清单。

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".

然后,将两个字母代码转换为您想要显示的字符串是一个简单的问题。所以如果是en,显示“English”。

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

希望这能帮助那些想要区分区域和当前选择语言的人。

EDIT

编辑

Worth to quote the header information from NSLocale.h:

引用来自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

People interested in app language take a look at @mindvision's answer

对应用语言感兴趣的人可以看看@mindvision的答案。

#2


258  

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

#3


73  

Solution for iOS 9:

解决方案iOS 9:

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

language = "en-US"

语言=“en - us”

NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];

languageDic will have the needed components

languageDic将有所需的组件。

NSString *countryCode = [languageDic objectForKey:@"kCFLocaleCountryCodeKey"];

countryCode = "US"

countryCode = "我们"

NSString *languageCode = [languageDic objectForKey:@"kCFLocaleLanguageCodeKey"];

languageCode = "en"

languageCode = "恩"

#4


64  

This will probably give you what you want:

这可能会给你想要的东西:

NSLocale *locale = [NSLocale currentLocale];

NSString *language = [locale displayNameForKey:NSLocaleIdentifier 
                                         value:[locale localeIdentifier]];

It will show the name of the language, in the language itself. For example:

它将显示语言的名称,在语言本身中。例如:

Français (France)
English (United States)

#5


27  

在iOS中获取当前的设备语言? The accepted, and the other answers all don't take into account that the preferred language can be another language than the device language.

被接受的和其他的答案都没有考虑到首选语言可能是另一种语言而不是设备语言。

The device language is the language in which operating system elements and Apple apps are presented.

设备语言是操作系统元素和苹果应用程序的语言。

The preferred language is the language the user would like to have apps localized in. Apple only provides a limited set of translations. If the preferred language is one language Apple translated their apps to, it will also be the device language. However if the user prefers a language for which Apple doesn't provide translations the device and preferred languages won't match. The device language will not be on first position in the preferred languages list.

首选语言是用户希望应用程序本地化的语言。苹果只提供有限的翻译。如果首选语言是一种语言,苹果将其应用程序翻译为,它也将是设备语言。然而,如果用户喜欢一种苹果不提供翻译的语言,设备和首选语言就不会匹配。设备语言不会位于首选语言列表中的第一个位置。

The following function will go through the preferred languages list and check if there is a translation in the Apple frameworks. The first language to have a translation is the device language. The function will return its language code.

下面的函数将通过首选语言列表,并检查Apple框架是否有翻译。第一个有翻译的语言是设备语言。函数将返回其语言代码。

func deviceLanguage() -> String? {
    let systemBundle: NSBundle = NSBundle(forClass: UIView.self)
    let englishLocale: NSLocale = NSLocale(localeIdentifier: "en")

    let preferredLanguages: [String] = NSLocale.preferredLanguages()

    for language: String in preferredLanguages {
        let languageComponents: [String : String] = NSLocale.componentsFromLocaleIdentifier(language)

        guard let languageCode: String = languageComponents[NSLocaleLanguageCode] else {
            continue
        }

        // ex: es_MX.lproj, zh_CN.lproj
        if let countryCode: String = languageComponents[NSLocaleCountryCode] {
            if systemBundle.pathForResource("\(languageCode)_\(countryCode)", ofType: "lproj") != nil {
                // returns language and country code because it appears that the actual language is coded within the country code aswell
                // for example: zh_CN probably mandarin, zh_HK probably cantonese
                return language
            }
        }

        // ex: English.lproj, German.lproj
        if let languageName: String = englishLocale.displayNameForKey(NSLocaleIdentifier, value: languageCode) {
            if systemBundle.pathForResource(languageName, ofType: "lproj") != nil {
                return languageCode
            }
        }

        // ex: pt.lproj, hu.lproj
        if systemBundle.pathForResource(languageCode, ofType: "lproj") != nil {
            return languageCode
        }
    }

    return nil
}

This works if the preferred language list is:

如果首选语言列表是:

  1. Afrikaans (iOS is not translated into Afrikaans)
  2. 南非荷兰语(iOS没有翻译成南非荷兰语)
  3. Spanish (Device Language)
  4. 西班牙语语言(设备)

The preferred language list can be edited in: Settings.app -> General -> Language & Region -> Preferred Language Order

首选语言列表可以在:设置中进行编辑。app ->通用->语言&区域->首选语言顺序。


You can than use the device language code and translate it into the language name. The following lines will print the device language in the device language. For example "Español" if the device is set to spanish.

您可以使用设备语言代码并将其转换为语言名称。以下几行将在设备语言中打印设备语言。例如“Espanol”,如果设备设置为西班牙语。

if let deviceLanguageCode: String = deviceLanguage() {
    let printOutputLanguageCode: String = deviceLanguageCode
    let printOutputLocale: NSLocale = NSLocale(localeIdentifier: printOutputLanguageCode)

    if let deviceLanguageName: String = printOutputLocale.displayNameForKey(NSLocaleIdentifier, value: deviceLanguageCode) {
        // keep in mind that for some localizations this will print a language and a country
        // see deviceLanguage() implementation above
        print(deviceLanguageName)
    }
} 

#6


14  

i use this

我用这个

    NSArray *arr = [NSLocale preferredLanguages];
for (NSString *lan in arr) {
    NSLog(@"%@: %@ %@",lan, [NSLocale canonicalLanguageIdentifierFromString:lan], [[[NSLocale alloc] initWithLocaleIdentifier:lan] displayNameForKey:NSLocaleIdentifier value:lan]);
}

ignore memory leak..

忽略了内存泄漏。

and result is

和结果是

2013-03-02 20:01:57.457 xx[12334:907] zh-Hans: zh-Hans 中文(简体中文)
2013-03-02 20:01:57.460 xx[12334:907] en: en English
2013-03-02 20:01:57.462 xx[12334:907] ja: ja 日本語
2013-03-02 20:01:57.465 xx[12334:907] fr: fr français
2013-03-02 20:01:57.468 xx[12334:907] de: de Deutsch
2013-03-02 20:01:57.472 xx[12334:907] nl: nl Nederlands
2013-03-02 20:01:57.477 xx[12334:907] it: it italiano
2013-03-02 20:01:57.481 xx[12334:907] es: es español

#7


12  

Translating language codes such as en_US into English (United States) is a built in feature of NSLocale and NSLocale does not care where you get the language codes from. So there really is no reason to implement your own translation as the accepted answer suggests.

将en_US这样的语言代码翻译成英语(美国)是一种内置的NSLocale, NSLocale不关心你从哪里得到语言代码。因此,没有必要按照公认的答案来实现你自己的翻译。

// Example code - try changing the language codes and see what happens
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
NSString *l1 = [locale displayNameForKey:NSLocaleIdentifier value:@"en"];
NSString *l2 = [locale displayNameForKey:NSLocaleIdentifier value:@"de"];
NSString *l3 = [locale displayNameForKey:NSLocaleIdentifier value:@"sv"];
NSLog(@"%@, %@, %@", l1, l2, l3);

Prints: English, German, Swedish

打印:英语,德语,瑞典

#8


7  

You can use the displayNameForKey:value: method of NSLocale:

您可以使用displayNameForKey:value: NSLocale的方法:

// get a French locale instance
NSLocale *frLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease];

// use it to get translated display names of fr_FR and en_US
NSLog(@"%@", [frLocale displayNameForKey:NSLocaleIdentifier value:@"fr_FR"]);
NSLog(@"%@", [frLocale displayNameForKey:NSLocaleIdentifier value:@"en_US"]);

This will print out:

这将打印出:

français (France)
anglais (États-Unis)

If you specify the same locale identifier for the initWithLocaleIdentifier: and also the displayNameForKey:value: method, then it will give you the native name of the language. I've discovered that if you remove the country code and use just fr and en, that it will also omit the country from the display name (on Mac OS X at least, not sure about iOS).

如果您为initWithLocaleIdentifier指定了相同的区域标识符:以及displayNameForKey:value:方法,那么它将给您提供该语言的本机名称。我发现,如果你删除了国家代码,只使用fr和en,那么它也会从显示名(至少在Mac OS X上,不确定iOS)中省略这个国家。

#9


7  

Even there's a better way to get current device language. Let us try it by below code -

即使有更好的方法来获得当前的设备语言。让我们用下面的代码来试试。

NSLog(@"Current Language - %@", [[NSLocale preferredLanguages] firstObject]);

Suggested by Abizern on here

这里是Abizern建议的。

#10


5  

Swift

To get current language of device

获取设备的当前语言。

NSLocale.preferredLanguages()[0] as String

To get application language

让应用程序语言

NSBundle.mainBundle().preferredLocalizations[0] as NSString

Note:

注意:

It fetches the language that you have given in CFBundleDevelopmentRegion of info.plist

它会获取你在info.plist的CFBundleDevelopmentRegion中给出的语言。

if CFBundleAllowMixedLocalizations is true in info.plist then first item of CFBundleLocalizations in info.plist is returned

如果cfbundleallowmixedlocalize在info中是正确的。plist然后第一项cfbundleloc的信息。plist返回

#11


5  

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.

我试图找到适合自己的解决方案。当我使用Locale.preferredLanguages。首先从应用程序设置中返回首选语言。

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

如果你想从用户设备设置中了解语言,你应该使用下面的字符串:

Swift 3

斯威夫特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
    }
}

#12


4  

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

为了获得用户设备的当前语言,请使用以下代码为我工作。

NSString * myString = [[NSLocale preferredlanguage]objectAtIndex:0];

#13


3  

For MonoTouch C# developers use:

对于MonoTouch c#开发人员使用:

NSLocale.PreferredLanguages.FirstOrDefault() ?? "en"

Note: I know this was an iOS question, but as I am a MonoTouch developer, the answer on this page led me in the right direction and I thought I'd share the results.

注意:我知道这是一个iOS的问题,但由于我是一个MonoTouch开发人员,这个页面上的答案引导我找到了正确的方向,我想我应该分享一下结果。

#14


3  

Simple Swift 3 function:

简单的快速3函数:

  @discardableResult
  func getLanguageISO() -> String {
    let locale = Locale.current
    guard let languageCode = locale.languageCode,
          let regionCode = locale.regionCode else {
        return "de_DE"
    }
    return languageCode + "_" + regionCode
  }

#15


2  

-(NSString *)returnPreferredLanguage { //as written text

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSArray *preferredLanguages = [defaults objectForKey:@"AppleLanguages"];
NSString *preferredLanguageCode = [preferredLanguages objectAtIndex:0]; //preferred device language code
NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"]; //language name will be in English (or whatever)
NSString *languageName = [enLocale displayNameForKey:NSLocaleIdentifier value:preferredLanguageCode]; //name of language, eg. "French"
return languageName;

}

#16


2  

In Swift:

迅速:

let languageCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String

#17


2  

Swift 3

斯威夫特3

let locale = Locale.current
let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String?
print(code!)

#18


1  

If you want to get only language here is my suggested answer:

如果你想只得到语言,我建议的答案是:

NSString *langplusreg = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString * langonly = [[langplusreg componentsSeparatedByString:@"-"] 
objectAtIndex:0];

In my case i just wanted only Locale language not locale region.

在我的例子中,我只需要Locale语言而不是Locale区域。

Output: If your Locale language is Japanese and locale region is Japan then:

输出:如果您的地区语言是日本人,地区是日本:

langplusreg = ja-JP

langplusreg = ja-JP

langonly = ja

langone =是

#19


1  

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

对于Swift 3.0以下代码可以用来回答您的问题:

 let language = Bundle.main.preferredLocalizations.first! as NSString

#20


0  

According to Apple documentation

根据苹果公司的文档

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];

#21


0  

Two letters format. Apple uses the ISO standard ISO-3166.

两个字母的格式。苹果使用ISO标准ISO-3166。

NSString *localeCountryCode = [[NSLocale autoupdatingCurrentLocale] objectForKey:NSLocaleCountryCode];

#22


0  

@amir response in Swift :

@amir回应Swift:

// Get language prefered by user
    let langageRegion = NSLocale.preferredLanguages().first!
    let languageDic = NSLocale.componentsFromLocaleIdentifier(langageRegion)
    let language = languageDic[NSLocaleLanguageCode]

#23


0  

For Swift 3:

为迅速3:

NSLocale.preferredLanguages[0] as String

NSLocale。preferredLanguages[0]是字符串

#24


0  

As of iOS 9, if you just want the language code without country code, you'll want this sort of helper function - since the language will contain the country code.

在ios9中,如果您只想要没有国家代码的语言代码,您将需要这种帮助函数——因为语言将包含国家代码。

// gets the language code without country code in uppercase format, i.e. EN or DE
NSString* GetLanguageCode()
{
    static dispatch_once_t onceToken;
    static NSString* lang;
    dispatch_once(&onceToken, ^
    {
        lang = [[[NSLocale preferredLanguages] objectAtIndex:0] uppercaseString];
        NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"^[A-Za-z]+" options:0 error:nil];
        NSTextCheckingResult* match = [regex firstMatchInString:lang options:0 range:NSMakeRange(0, lang.length)];
        if (match.range.location != NSNotFound)
        {
            lang = [lang substringToIndex:match.range.length];
        }
    });
    return lang;
}

#25


0  

Obviously, the solutions relying, for example, on

显然,解决方案依赖于,例如,on。

[[NSLocale preferredLanguages] objectAtIndex:0]

usually work fine and return the current device language.

通常工作良好并返回当前设备语言。

But it could be misleading in some cases :

但在某些情况下可能会产生误导:

If the app in which you want to get this value has already changed the language, for example with this kind of code :

如果你想要得到这个值的应用程序已经改变了语言,例如使用这种代码:

NSString *lg = @"en"; // or anything like @"en", @"fr", etc.
[[NSUserDefaults standardUserDefaults] 
    setObject:[NSArray arrayWithObjects:lg, nil]  
    forKey:@"AppleLanguages"]

In this case, [NSLocale preferredLanguages] actually returns the preferred language set (and used) in this particular app, not the current device language !

在这种情况下,[NSLocale preferredLanguages]实际上会在这个特定的应用程序中返回首选语言集(和使用),而不是当前的设备语言!

And... in this case the only way to properly get the actual current device language (and not that previously set in the app), is to firstly clear the key @"appleLanguages" in NSUserDefaults, like this :

和…在这种情况下,正确获取实际当前设备语言(而不是之前在应用程序中设置的)的唯一方法是首先清除NSUserDefaults中的关键@“appleLanguages”,如下所示:

[[NSUserDefaults standardUserDefaults]removeObjectForKey:@"AppleLanguages"];

Then, [NSLocale preferredLanguages] now returns the correct value.

然后,[NSLocale preferredLanguages]现在返回正确的值。

Hope this help.

希望这个有帮助。

#26


0  

If you're looking for preferred language code ("en", "de", "es" ...), and localized preferred language name (for current locale), here's a simple extension in Swift:

如果您正在寻找首选语言代码(“en”、“de”、“es”…),以及本地化的首选语言名称(对于当前语言环境),下面是Swift的简单扩展:

extension Locale {
static var preferredLanguageIdentifier: String {
    let id = Locale.preferredLanguages.first!
    let comps = Locale.components(fromIdentifier: id)
    return comps.values.first!
}

static var preferredLanguageLocalizedString: String {
    let id = Locale.preferredLanguages.first!
    return Locale.current.localizedString(forLanguageCode: id)!
}

}

}

#27


0  

SWIFT-4

SWIFT-4

 // To get device default selected language. It will print like short name of zone. For english, en or spain, es.



let language = Bundle.main.preferredLocalizations.first! as NSString
    print("device language",language)

#28


0  

Updated answer for Swift 4

更新快4的答案。

let language = Bundle.main.preferredLocalizations.first