Obtener el idioma del dispositivo actual en iOS?


Me gustaría mostrar el idioma actual que está utilizando la interfaz de usuario del dispositivo. ¿Qué código usaría?

Quiero esto como un NSString en formato completamente escrito. (No @"es_US")

EDITAR: Para aquellos que conducen por, hay un montón de comentarios útiles aquí, ya que la respuesta ha evolucionado con las nuevas versiones de iOS.

Author: Bhavin Ramani, 2010-10-12

28 answers

Las soluciones proporcionadas realmente devolverán la región actual del dispositivo, no el idioma seleccionado actualmente. Estos son a menudo uno y el mismo. Sin embargo, si estoy en América del Norte y establezco mi idioma en japonés, mi región seguirá siendo el inglés (Estados Unidos). Para recuperar el idioma seleccionado actualmente, puede hacer:

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

Esto devolverá un código de dos letras para el idioma seleccionado actualmente. "en" para inglés, "es" para español, "de" para alemán, etc. Para más ejemplos, por favor vea esta entrada de Wikipedia (en particular, la columna 639-1):

Lista de códigos ISO 639-1

Entonces es una simple cuestión de convertir los códigos de dos letras a la cadena que le gustaría mostrar. Así que si es "en", mostrar "Inglés".

Espero que esto ayude a alguien que está buscando diferenciar entre la región y el idioma seleccionado actualmente.

EDITAR

Vale la pena citar la información del encabezado de 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

Las personas interesadas en el idioma de la aplicación echen un vistazo a La respuesta de@mindvision

 768
Author: Dubron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-18 15:40:19

La respuesta seleccionada devuelve el idioma del dispositivo actual, pero no el idioma utilizado en la aplicación. Si no proporciona una localización en su aplicación para el idioma preferido del usuario, se utiliza la primera localización disponible, ordenada por el orden preferido del usuario.

Para descubrir el idioma actual seleccionado dentro de sus localizaciones use

[[NSBundle mainBundle] preferredLocalizations];

Ejemplo:

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

Swift:

let language = NSBundle.mainBundle().preferredLocalizations.first as NSString
 265
Author: mindvision,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-24 08:54:17

Solución para iOS 9:

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

Language = "en-US"

NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];

LanguageDic tendrá los componentes necesarios

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

CountryCode = "US"

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

LanguageCode = "es"

 75
Author: amir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 22:08:59

Esto probablemente te dará lo que quieres:

NSLocale *locale = [NSLocale currentLocale];

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

Mostrará el nombre del idioma, en el idioma en sí. Por ejemplo:

Français (France)
English (United States)
 64
Author: Philippe Leybaert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-11 22:04:52

advertenciaLas respuestas aceptadas y las demás no tienen en cuenta que el idioma preferido puede ser otro idioma que el idioma del dispositivo.

El idioma del dispositivo es el idioma en el que se presentan los elementos del sistema operativo y las aplicaciones de Apple.

El idioma preferido es el idioma en el que el usuario desea que se localicen las aplicaciones. Apple solo proporciona un conjunto limitado de traducciones. Si el idioma preferido es un idioma Apple traducido a sus aplicaciones, también será el idioma del dispositivo. Sin embargosi el usuario prefiere un idioma para el que Apple no proporciona traducciones, el dispositivo y los idiomas preferidos no coincidirán con. El idioma del dispositivo no estará en la primera posición de la lista de idiomas preferidos.

La siguiente función revisará la lista de idiomas preferidos y verificará si hay una traducción en los frameworks de Apple. El primer idioma en tener una traducción es el dispositivo idioma. La función devolverá su código de idioma.

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
}

Esto funciona si la lista de idiomas preferidos es:

  1. Afrikaans (iOS no se traduce al Afrikaans)
  2. Español (Idioma del Dispositivo)

La lista de idiomas preferidos se puede editar en: Settings.aplicación - > General - > Idioma y Región - > Orden de Idioma preferido


Puede utilizar el código de idioma del dispositivo y traducirlo al nombre del idioma. Las siguientes líneas imprimirán el idioma del dispositivo en el idioma del dispositivo. Por ejemplo, "Español" si el dispositivo está configurado en 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)
    }
} 
 29
Author: dreamlab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-22 23:26:24

Yo uso esto

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

Ignorar pérdida de memoria..

Y el resultado es

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
 13
Author: enzoyang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-02 12:39:41

Traducir códigos de idioma como en_USa Inglés (Estados Unidos) es una característica incorporada de NSLocale y NSLocale no le importa de dónde obtenga los códigos de idioma. Así que realmente no hay razón para implementar su propia traducción como sugiere la respuesta aceptada.

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

Impresiones: Inglés, alemán, Sueco

 12
Author: Erik B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-24 14:14:26

Incluso hay una mejor manera de obtener el idioma actual del dispositivo. Vamos a intentarlo por debajo del código -

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

Sugerido por Abizern en aquí

 8
Author: Praveenkumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-28 09:58:07

Puede utilizar el método displayNameForKey:value: de 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"]);

Esto se imprimirá:

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

Si especifica el mismo identificador de configuración regional para el método initWithLocaleIdentifier: y también para el método displayNameForKey:value:, entonces le dará el nombre nativo del idioma. He descubierto que si eliminas el código de país y usas solo fr y en, también omitirá el país del nombre para mostrar (al menos en Mac OS X, no estoy seguro de iOS).

 7
Author: dreamlax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-11 22:05:41

Swift

Para obtener el idioma actual del dispositivo

NSLocale.preferredLanguages()[0] as String

Para obtener el idioma de la aplicación

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

Nota:

Obtiene el lenguaje que has dado en CFBundleDevelopmentRegion de info.plist

Si CFBundleAllowMixedLocalizations es true en info.plist then first item of CFBundleLocalizations in info.plist se devuelve

 5
Author: Durai Amuthan.H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-05 14:06:21

Traté de encontrar la solución correcta para mí. Cuando uso Locale.preferredLanguages.first se devolvió el idioma preferido de la configuración de la aplicación.

Si desea conocer el idioma desde la configuración del dispositivo del usuario, debe usar la siguiente cadena:

Swift 3

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

Para desenvolver y usar mira la línea de abajo:

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

    // For example
    if currentDeviceLanguage == "he" {
        UIView.appearance().semanticContentAttribute = .forceRightToLeft
    } else {
        UIView.appearance().semanticContentAttribute = .forceLeftToRight
    }
}
 5
Author: Roman Romanenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-27 23:55:52

Para obtener el idioma actual del dispositivo del usuario use el siguiente código it que funcionó para mí.

NSString * myString = [[NSLocale preferredlanguage]objectAtIndex:0];
 4
Author: shailendra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-27 12:51:10

Para desarrolladores de C# MonoTouch use:

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

Nota: Sé que esta fue una pregunta de iOS, pero como soy un desarrollador MonoTouch, la respuesta en esta página me llevó en la dirección correcta y pensé en compartir los resultados.

 3
Author: Chuck Savage,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-20 18:27:21

En Swift:

let languageCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String
 3
Author: lee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-06 07:40:36

Función simple 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
  }
 3
Author: Sasha Prokhorenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-14 15:31:36
-(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;

}
 2
Author: Johnny Rockex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-08 13:39:28

Swift 3

let locale = Locale.current
let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String?
print(code!)
 2
Author: Tarik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-05 00:06:39

Si está buscando el código de idioma preferido ("en"," de"," es"...), y el nombre del idioma preferido localizado (para la configuración regional actual), aquí hay una extensión simple en 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)!
}

}

 2
Author: Jovan Stankovic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 23:48:44

Si desea obtener solo lenguaje aquí está mi respuesta sugerida:

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

En mi caso solo quería idioma Locale no región locale.

Salida: Si su idioma local es japonés y la región local es Japón, entonces:

Langplusreg = ja-JP

Langonly = ja

 1
Author: Danboz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-08 05:45:44

Para Swift 3.0 se puede usar el siguiente código para responder a su pregunta:

 let language = Bundle.main.preferredLocalizations.first! as NSString
 1
Author: Apurv Soni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-10 08:09:32

Según la documentación de Apple

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];
 0
Author: Max Tymchii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-16 11:32:44

Formato de dos letras. Apple utiliza la norma ISO ISO-3166.

NSString *localeCountryCode = [[NSLocale autoupdatingCurrentLocale] objectForKey:NSLocaleCountryCode];
 0
Author: Jakub Truhlář,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-31 08:51:44

@amir respuesta en Swift:

// Get language prefered by user
    let langageRegion = NSLocale.preferredLanguages().first!
    let languageDic = NSLocale.componentsFromLocaleIdentifier(langageRegion)
    let language = languageDic[NSLocaleLanguageCode]
 0
Author: CedricSoubrie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-30 20:06:00

Para Swift 3:

NSLocale.preferredLanguages [0] como String

 0
Author: Bill Chan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-04 16:31:35

A partir de iOS 9, si solo desea el código de idioma sin código de país, querrá este tipo de función auxiliar, ya que el idioma contendrá el código de país.

// 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;
}
 0
Author: jjxtra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-24 00:07:21

Obviamente, las soluciones basadas, por ejemplo, en

[[NSLocale preferredLanguages] objectAtIndex:0]

Normalmente funciona bien y devuelve el idioma del dispositivo actual.

Pero podría ser engañoso en algunos casos:

Si la app en la que quieres obtener este valor ya ha cambiado el idioma, por ejemplo con este tipo de código :

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

En este caso, [NSLocale preferredLanguages] en realidad devuelve el conjunto de idioma preferido (y utilizado) en esta aplicación en particular, no el dispositivo actual ¡lenguaje !

Y... en este caso, la única manera de obtener correctamente el idioma actual del dispositivo (y no el establecido previamente en la aplicación), es primero borrar la clave @ "AppleLanguages" en NSUserDefaults, de la siguiente manera :

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

Entonces, [NSLocale preferredLanguages] ahora devuelve el valor correcto.

Espero que esto ayude.

 0
Author: Chrysotribax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-07 14:54:30

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
Author: anshul-systematix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-17 13:48:15

Respuesta Actualizada para Swift 4

let language = Bundle.main.preferredLocalizations.first
 0
Author: Md. Ibrahim Hassan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-26 11:51:01