Getting current device language in iOS?

前端 未结 30 2330
星月不相逢
星月不相逢 2020-11-22 09:10

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

相关标签:
30条回答
  • 2020-11-22 09:26

    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)
    
    0 讨论(0)
  • 2020-11-22 09:28

    In Swift:

    let languageCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String
    
    0 讨论(0)
  • 2020-11-22 09:29

    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

    0 讨论(0)
  • 2020-11-22 09:29

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

    NSString * myString = [[NSLocale preferredlanguage]objectAtIndex:0];
    
    0 讨论(0)
  • 2020-11-22 09:29

    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.

    0 讨论(0)
  • 2020-11-22 09:30

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题