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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3910244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:53:04  来源:igfitidea点击:

Getting current device language in iOS?

iosobjective-ccocoa-touchnslocale

提问by Moshe

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 NSStringin 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 版本而发展。

回答by Dubron

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 的回答

回答by mindvision

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

回答by amir

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"

国家代码 = "美国"

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

languageCode = "en"

语言代码 = "zh"

回答by Philippe Leybaert

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)

回答by dreamlab

warningThe 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 languageis the language in which operating system elements and Apple apps are presented.

所述设备的语言是在其中操作系统元件和苹果的应用程序呈现的语言。

The preferred languageis 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. Howeverif 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.

首选语言是用户想要在苹果只提供了一组有限的翻译本地化的应用程序的语言。如果首选语言是 Apple 将其应用程序翻译成的一种语言,那么它也将是设备语言。但是,如果用户更喜欢 Apple 不提供翻译的语言,则设备和首选语言将不匹配。设备语言不会在首选语言列表中排在第一位。

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. Spanish (Device Language)
  1. 南非荷兰语(iOS 未翻译成南非荷兰语)
  2. 西班牙语(设备语言)

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

首选语言列表,可以在编辑:Settings.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.

然后您可以使用设备语言代码并将其翻译成语言名称。以下几行将以设备语言打印设备语言。例如“Espa?ol”,如果设备设置为西班牙语。

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

回答by enzoyang

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

回答by Erik B

Translating language codes such as en_USinto English (United States)is a built in feature of NSLocaleand NSLocaledoes 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英语(美国)是一个内置在功能NSLocaleNSLocale不关心你在哪里得到的语言代码。因此,确实没有理由像接受的答案所暗示的那样实施您自己的翻译。

// 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

印刷品:英语、德语、瑞典语

回答by Praveenkumar

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

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

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

Suggested by Abizernon here

Abilern此处推荐

回答by dreamlax

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 frand 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:方法指定相同的区域设置标识符,那么它将为您提供语言的本地名称。我发现如果您删除国家/地区代码并仅使用frand en,它也会从显示名称中省略国家/地区(至少在 Mac OS X 上,不确定 iOS)。

回答by Durai Amuthan.H

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 CFBundleDevelopmentRegionof info.plist

它获取您在info.plist 的CFBundleDevelopmentRegion中提供的语言

if CFBundleAllowMixedLocalizationsis true in info.plist then first item of CFBundleLocalizationsin info.plist is returned

如果info.plist 中的CFBundleAllowMixedLocalizations为真,则返回 info.plist中CFBundleLocalizations 的第一项