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

发布于 2024-09-27 11:53:24 字数 147 浏览 8 评论 0 原文

我想显示设备用户界面当前使用的语言。我会使用什么代码?

我希望将其作为完全拼写格式的 NSString 。 (不是@“en_US”)

编辑:对于那些路过的人来说,这里有大量有用的评论,因为答案随着新的 iOS 版本而演变。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

自由如风 2024-10-04 11:53:24

提供的解决方案实际上将返回设备的当前区域 - 而不是当前选择的语言。这些通常是同一个。但是,如果我在北美并将语言设置为日语,则我的区域仍将是英语(美国)。为了检索当前选择的语言,您可以执行以下操作:

NSString * language = [[NSLocale preferredLanguages] firstObject];

这将为当前选择的语言返回两个字母的代码。 “en”代表英语,“es”代表西班牙语,“de”代表德语等。有关更多示例,请参阅此维基百科条目(特别是 639-1 列):

ISO 639-1 代码列表

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

编辑

值得引用 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

对应用程序语言感兴趣的人可以看看 @mindvision 的回答< /a>

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

List of ISO 639-1 codes

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

EDIT

Worth to quote the header information from 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

没有你我更好 2024-10-04 11:53:24

所选答案返回当前设备语言,但不是应用程序中使用的实际语言。如果您未在应用中提供用户首选语言的本地化,则将使用按用户首选顺序排序的第一个可用本地化。

要发现本地化中选择的当前语言,请使用

[[NSBundle mainBundle] preferredLocalizations];

示例:

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

Swift:

let language = NSBundle.mainBundle().preferredLocalizations.first as NSString

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
一笑百媚生 2024-10-04 11:53:24

iOS13、Swift 5+

Locale.preferredLanguages.first

iOS 9 解决方案:

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

language = "en-US"

NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];

languageDic 将包含所需的组件

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

countryCode = "US"

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

languageCode = "en"

iOS13, Swift 5+

Locale.preferredLanguages.first

Solution for iOS 9:

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

language = "en-US"

NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];

languageDic will have the needed components

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

countryCode = "US"

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

languageCode = "en"

玩套路吗 2024-10-04 11:53:24

这可能会给你你想要的:

NSLocale *locale = [NSLocale currentLocale];

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

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

Français (France)
English (United States)

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)
清风疏影 2024-10-04 11:53:24

warning 接受的答案和其他答案都没有考虑到首选语言可以是另一种语言比设备语言

设备语言是操作系统元素和Apple应用程序呈现的语言。

首选语言是用户希望应用程序本地化时使用的语言。Apple 仅提供有限的翻译集。如果首选语言是苹果将其应用程序翻译成的一种语言,那么它也将是设备语言。 但是,如果用户喜欢 Apple 未提供翻译的语言,则设备和首选语言将不匹配。设备语言不会位于首选语言列表中的第一位。

以下函数将遍历首选语言列表并检查 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
}

如果首选语言列表为:

  1. 南非荷兰语(iOS 未翻译为南非荷兰语)
  2. 西班牙语(设备语言)

则此功能有效。 首选语言列表可以是编辑位置:Settings.app ->一般->语言与地区->首选语言顺序


您可以使用设备语言代码并将其翻译为语言名称。以下行将以设备语言打印设备语言。例如,如果设备设置为西班牙语,则为“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)
    }
} 

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

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)

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


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.

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)
    }
} 
我们只是彼此的过ke 2024-10-04 11:53:24

iOS13、Swift 5+、WWDC2019
https://developer.apple.com/videos/play/wwdc2019/403/

用户可以独立于操作系统语言选择应用程序的首选语言。

您可以使用这些:

    // Returns a list of the user's preferred languages.
    // Maybe more than (or none of) your app supports!
    Locale.preferredLanguages

    // a subset of this bundle's localizations, re-ordered into the preferred order
    // for this process's current execution environment; the main bundle's preferred localizations
    // indicate the language (of text) the user is most likely seeing in the UI
    Bundle.main.preferredLocalizations



    // The current running app language
    Bundle.main.preferredLocalizations.first

    // list of language names this bundle appears to be localized to
    Bundle.main.localizations

iOS13, Swift 5+, WWDC2019
https://developer.apple.com/videos/play/wwdc2019/403/

Users can select the preferred language of an app independently from the OS language.

You can use these:

    // Returns a list of the user's preferred languages.
    // Maybe more than (or none of) your app supports!
    Locale.preferredLanguages

    // a subset of this bundle's localizations, re-ordered into the preferred order
    // for this process's current execution environment; the main bundle's preferred localizations
    // indicate the language (of text) the user is most likely seeing in the UI
    Bundle.main.preferredLocalizations



    // The current running app language
    Bundle.main.preferredLocalizations.first

    // list of language names this bundle appears to be localized to
    Bundle.main.localizations
自此以后,行同陌路 2024-10-04 11:53:24

我使用这个

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

忽略内存泄漏..

结果是

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

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
灯下孤影 2024-10-04 11:53:24

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

打印:英语、德语、瑞典语

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.

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

云柯 2024-10-04 11:53:24

我试图为自己找到正确的解决方案。当我使用 Locale.preferredLanguages.first 时,从您的应用设置中返回了首选语言。

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

Swift 3

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

要解开并使用,请查看下面的行:

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

    // For example
    if currentDeviceLanguage == "he" {
        UIView.appearance().semanticContentAttribute = .forceRightToLeft
    } else {
        UIView.appearance().semanticContentAttribute = .forceLeftToRight
    }
}

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
    }
}
秋日私语 2024-10-04 11:53:24

甚至有更好的方法来获取当前的设备语言。让我们通过下面的代码来尝试一下 -

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

Abizern此处

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 Abizern on here

野侃 2024-10-04 11:53:24

您可以使用 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"]);

这将打印出:

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

如果为 initWithLocaleIdentifier: 以及displayNameForKey:value: 方法,然后它将为您提供该语言的本机名称。我发现,如果您删除国家/地区代码并仅使用 fren,它也会从显示名称中省略国家/地区(至少在 Mac OS X 上) ,不确定 iOS)。

You can use the displayNameForKey:value: method of 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).

怎言笑 2024-10-04 11:53:24

Swift

获取设备的当前语言

NSLocale.preferredLanguages()[0] as String

获取应用程序语言

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

注意:

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

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

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

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

拥抱没勇气 2024-10-04 11:53:24

为了获取用户设备当前的语言,请使用以下对我有用的代码。

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

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

NSString * myString = [[NSLocale preferredlanguage]objectAtIndex:0];
沙与沫 2024-10-04 11:53:24

如果您正在寻找首选语言代码(“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)!
    }
}

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:

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)!
    }
}
百合的盛世恋 2024-10-04 11:53:24

对于 MonoTouch C# 开发人员,请使用:

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

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

For MonoTouch C# developers use:

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.

童话 2024-10-04 11:53:24

在 Swift 中:

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

In Swift:

let languageCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String
长梦不多时 2024-10-04 11:53:24

斯威夫特3

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

Swift 3

let locale = Locale.current
let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String?
print(code!)
水染的天色ゝ 2024-10-04 11:53:24

简单的 Swift 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
}

Simple Swift 3 function:

@discardableResult
func getLanguageISO() -> String {
    let locale = Locale.current
    guard let languageCode = locale.languageCode,
          let regionCode = locale.regionCode else {
        return "de_DE"
    }
    return languageCode + "_" + regionCode
}
谜兔 2024-10-04 11:53:24
-(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;

}
-(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;

}
罪歌 2024-10-04 11:53:24

如果您只想获得语言,这是我建议的答案:

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

就我而言,我只想要区域设置语言而不是区域设置区域。

输出:
如果您的区域设置语言是日语并且区域设置区域是日本,则:

langplusreg = ja-JP

langonly = ja

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.

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

langplusreg = ja-JP

langonly = ja

柠檬心 2024-10-04 11:53:24

显然,例如,依赖的解决方案

[[NSLocale preferredLanguages] objectAtIndex:0]

通常可以正常工作并返回当前的设备语言。

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

如果您想要获取此值的应用程序已经更改了语言,例如使用这种代码:

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

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

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

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

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

希望这有帮助。

Obviously, the solutions relying, for example, 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 !

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 standardUserDefaults]removeObjectForKey:@"AppleLanguages"];

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

Hope this help.

余生共白头 2024-10-04 11:53:24

在 Swift 4.2 和 Xcode 10.1 中

let language = NSLocale.preferredLanguages[0]
debugPrint(language)//en

在 Swift 5.x 中

let langStr = Locale.current.languageCode
debugPrint(langStr ?? "") //en  el

In Swift 4.2 and Xcode 10.1

let language = NSLocale.preferredLanguages[0]
debugPrint(language)//en

In Swift 5.x

let langStr = Locale.current.languageCode
debugPrint(langStr ?? "") //en  el
梦行七里 2024-10-04 11:53:24

我实际上误读了原来的问题,认为它要求“应用程序 UI”语言(这就是我在谷歌上搜索的内容),而不是“设备 UI”,在这种情况下,最好的答案将是使用 preferredLocalizations,但这些答案仍然给你一个代码,还有一个步骤来获得一个漂亮的字符串来显示。
因此,虽然“设备 UI”语言已经得到解答,但如果您想为当前正在使用的您支持的 UI 语言显示一个漂亮的字符串,显然最简单的解决方案是:

NSLocalizedString(@"currentLanguage", @"")

在您的每一个 UI 本地化中,您都有完全按照您希望的显示方式指定它。例如,在 en 版本的 .strings 文件中,您将拥有:

"currentLanguage"="English";

fr 版本的 .strings 中> 您拥有的文件:

"currentLanguage"="Francais";

等。不要弄乱代码等,您可以创建自己的字符串以很好地匹配您的用户界面。

I actually misread the original question, thought it asked for the "app UI" language (that's what I had googled for), not the "device UI", in which case the best answers would be the ones using preferredLocalizations, but those answers still give you a code, there is one more step to get a nice string to display.
So, while the "device UI" language is already answered, if you want to display a nice string for which of the UI languages you support is currently in use, obviously the simplest solution is:

NSLocalizedString(@"currentLanguage", @"")

Where in every one of your UI localizations you have specified it exactly the way you want it shown. E.g. in the en version of your .strings file you'd have:

"currentLanguage"="English";

in your fr version of the .strings file you'd have:

"currentLanguage"="Francais";

etc. No messing with codes etc, you make your own strings to nicely match your UI.

傻比既视感 2024-10-04 11:53:24

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)

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)
浅浅淡淡 2024-10-04 11:53:24

@amir 用 Swift 回应:

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

@amir response in Swift :

// Get language prefered by user
let langageRegion = NSLocale.preferredLanguages().first!
let languageDic = NSLocale.componentsFromLocaleIdentifier(langageRegion)
let language = languageDic[NSLocaleLanguageCode]
木緿 2024-10-04 11:53:24

根据 Apple 文档

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

According to Apple documentation

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];
锦欢 2024-10-04 11:53:24

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

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

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

NSString *localeCountryCode = [[NSLocale autoupdatingCurrentLocale] objectForKey:NSLocaleCountryCode];
岁月染过的梦 2024-10-04 11:53:24

对于 Swift 3:

NSLocale.preferredLanguages[0] 作为字符串

For Swift 3:

NSLocale.preferredLanguages[0] as String

不必了 2024-10-04 11:53:24

从 iOS 9 开始,如果您只想要没有国家/地区代码的语言代码,那么您将需要这种辅助函数 - 因为语言将包含国家/地区代码。

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

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.

// 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;
}
記憶穿過時間隧道 2024-10-04 11:53:24

更新了 Swift 4 的答案

let language = Bundle.main.preferredLocalizations.first

Updated answer for Swift 4

let language = Bundle.main.preferredLocalizations.first
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文