Getting current device language in iOS?

前端 未结 30 2743
星月不相逢
星月不相逢 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:34

    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.

提交回复
热议问题