首页 文章

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

提问于
浏览
402

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

我希望这是一个完全拼写格式的 NSString . (不是@ "en_US")

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

28 回答

  • 3

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

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

    根据Apple documentation

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

    两个字母格式 . Apple使用ISO standard ISO-3166 .

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

    Swift中的@amir响应:

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

    对于Swift 3:

    NSLocale.preferredLanguages [0] as String

  • 0

    Swift 3

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

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

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

    这将返回当前所选语言的双字母代码 . 英语为“en”,西班牙语为“es”,德语为“de”等 . 有关更多示例,请参阅此Wikipedia条目(特别是639-1专栏):

    List of ISO 639-1 codes

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

    希望这可以帮助那些希望区分区域和当前所选语言的人 .

    EDIT

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

    对app语言感兴趣的人看看@mindvision's answer

  • 78

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

    要发现在本地化中使用的当前语言

    [[NSBundle mainBundle] preferredLocalizations];
    

    例:

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

    迅速:

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

    Solution for 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”

  • 64

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

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

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

    Français (France)
    English (United States)
    
  • 0

    warning
    接受了,其他答案都没有考虑到 preferred language can be another language than the device language .

    device language 是显示操作系统元素和Apple应用程序的语言 .

    preferred language 是用户希望将应用程序本地化的语言.Apple仅提供有限的翻译集 . 如果首选语言是Apple将其应用翻译成的一种语言,那么它也将是设备语言 . However 如果用户更喜欢Apple不提供翻译的语言 device and preferred languages won't match . 设备语言不会位于首选语言列表的第一个位置 .

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

    如果首选语言列表是:

    • 南非荷兰语(iOS未翻译成南非荷兰语)

    • 西班牙语(设备语言)

    preferred language list 可以是 edited in :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)
        }
    }
    
  • 13

    我用这个

    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
    
  • 773

    en_US 等语言代码翻译为 English (United States)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);
    

    印刷品: English, German, Swedish

  • 0

    即使有更好的方法来获取当前的设备语言 . 让我们通过以下代码尝试 -

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

    建议Abizernhere

  • 0

    您可以使用NSLocaledisplayNameForKey:value: 方法:

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

  • 5

    斯威夫特

    获取设备的当前语言

    NSLocale.preferredLanguages()[0] as String
    

    获得申请语言

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

    注意:

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

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

  • 3

    我试图为自己找到合适的解决方案 . 当我使用 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
        }
    }
    
  • 0

    要获取用户设备当前语言,请使用以下代码对我有用 .

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

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

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

    注意:我知道这是一个iOS问题,但由于我是MonoTouch开发人员,本页面的答案使我朝着正确的方向前进,我想我会分享结果 .

  • 12

    Swift

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

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

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

    }

  • 29
    -(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;
    
    }
    
  • 3

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

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

    在我的情况下,我只想要Locale语言而不是语言环境区域 .

    输出:如果您的区域设置语言是日语,区域设置区域是日本,那么:

    langplusreg = ja-JP

    langonly = ja

  • 4

    从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;
    }
    
  • 5

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

    [[NSLocale preferredLanguages] objectAtIndex:0]
    

    通常工作正常并返回当前的设备语言 .

    But it could be misleading in some cases :

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

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

    在这种情况下,[NSLocale preferredLanguages] actually returns the preferred language set (and used) in this particular app, not the current device language !

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

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

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

    希望这有帮助 .

  • 2

    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)
    
  • 8

    Updated answer for Swift 4

    let language = Bundle.main.preferredLocalizations.first
    

相关问题