Uzyskiwanie bieżącego języka urządzenia w systemie iOS?

Chciałbym pokazać aktualny język, którego używa Interfejs urządzenia. Jakiego kodu bym użył?

Chcę to jako NSString w pełni zapisanym formacie. (Nie @ "en_US")

EDIT: dla tych, którzy przejeżdżają obok, jest tu mnóstwo przydatnych komentarzy, ponieważ odpowiedź ewoluowała wraz z nowymi wydaniami iOS.

Author: Bhavin Ramani, 2010-10-12

28 answers

Dostarczone rozwiązania zwrócą bieżący region urządzenia, a nie aktualnie wybrany język. Często są one takie same. Jeśli jednak jestem w Ameryce Północnej i ustawiłem mój język na japoński, moim regionem nadal będzie Angielski (Stany Zjednoczone). Aby pobrać aktualnie wybrany język, możesz wykonać:

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

Zwróci dwuliterowy kod dla aktualnie wybranego języka. "en" dla angielskiego, " es "dla hiszpańskiego," de " dla niemieckiego, itp. Więcej przykłady, patrz ten wpis w Wikipedii (w szczególności kolumna 639-1):

Lista kodów ISO 639-1

Wtedy jest prosta sprawa konwersji dwuliterowych kodów na ciąg, który chcesz wyświetlić. Więc jeśli jest "en", wyświetl "angielski".

Mam nadzieję, że pomoże to komuś, kto chce odróżnić region od aktualnie wybranego języka.

EDIT

Warto zacytować informacje nagłówka z 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
[[2]} Osoby zainteresowane językiem aplikacji Zobacz @mindvision ' s answer
 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-18 15:40:19

Wybrana odpowiedź zwraca bieżący język urządzenia, ale nie rzeczywisty język używany w aplikacji. Jeśli nie podasz lokalizacji w aplikacji dla preferowanego języka użytkownika, używana jest pierwsza dostępna lokalizacja, zamówiona według preferowanego zamówienia Użytkownika.

Aby odkryć bieżący język wybrany w Twojej lokalizacji użyj

[[NSBundle mainBundle] preferredLocalizations];

Przykład:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-24 08:54:17

Rozwiązanie dla iOS 9:

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

Language = "en-US"

NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];

LanguageDic będzie miał potrzebne komponenty

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

CountryCode = "US"

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

LanguageCode = " en "

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-04 22:08:59

To prawdopodobnie da ci to, czego chcesz:

NSLocale *locale = [NSLocale currentLocale];

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

Wyświetli nazwę języka, w samym języku. Na przykład:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-11 22:04:52

OstrzeżenieAkceptowane i pozostałe odpowiedzi nie biorą pod uwagę, że preferowany język może być innym językiem niż język urządzenia.

Język urządzenia jest językiem, w którym prezentowane są elementy systemu operacyjnego i aplikacje Apple.

The preferowany język jest językiem, w którym użytkownik chciałby mieć zlokalizowane aplikacje. Apple zapewnia tylko ograniczony zestaw tłumaczeń. Jeśli preferowanym językiem jest jeden język Apple przetłumaczone ich aplikacje, będzie to również język urządzenia. jednakże jeśli użytkownik preferuje język, dla którego Apple nie zapewnia tłumaczeń, urządzenie i preferowane języki nie będą zgodne . Język urządzenia nie znajdzie się na pierwszej pozycji na liście preferowanych języków.

Następująca funkcja przejrzy listę preferowanych języków i sprawdzi, czy w strukturach Apple jest tłumaczenie. Pierwszym językiem, który ma tłumaczenie, jest urządzenie język. Funkcja zwróci kod języka.

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
}

To działa, jeśli preferowaną listą języków jest:

    Nie jest to jednak żaden problem, ponieważ nie jest to możliwe.]}
  1. Hiszpański (Język Urządzenia)

Lista preferowanych języków może być edytowana w: Settings.aplikacja - > Ogólne - > Język i Region - > preferowana kolejność języków


Możesz użyć kodu języka urządzenia i przetłumaczyć go na nazwa języka. Następujące linie wyświetlą język urządzenia w języku urządzenia. Na przykład "Español", jeśli urządzenie jest ustawione na hiszpański.

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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-22 23:26:24

Używam tego

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

A wynikiem jest

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/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-02 12:39:41

Tłumaczenie kodów językowych, takich jak en_US na Angielski (Stany Zjednoczone) jest wbudowaną funkcją NSLocale i NSLocale nie obchodzi, skąd masz kody językowe. Tak więc naprawdę nie ma powodu, aby wdrożyć własne tłumaczenie, jak sugeruje przyjęta odpowiedź.

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

Druki: Angielski, Niemiecki, Szwedzki

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-24 14:14:26

Nawet istnieje lepszy sposób, aby uzyskać bieżący język urządzenia. Wypróbujmy poniższy kod -

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

Zasugerował: Abizern on here

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-28 09:58:07

Możesz użyć metody displayNameForKey:value: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"]);

To wydrukuje:

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

Jeśli podasz ten sam IDENTYFIKATOR locale dla metody initWithLocaleIdentifier: oraz metody displayNameForKey:value:, to poda ona natywną nazwę języka. Odkryłem, że jeśli usuniesz kod kraju i użyjesz tylko fr i en, to również pominie kraj z wyświetlanej nazwy(przynajmniej na Mac OS X, nie jestem pewien co do 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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-11 22:05:41

Swift

aby uzyskać bieżący język urządzenia

NSLocale.preferredLanguages()[0] as String

aby uzyskać język aplikacji

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

Uwaga:

Pobiera język, który podałeś w CFBundleDevelopmentRegion informacji.plist

If CFBundleAllowMixedLocalizations is true in info.plist następnie pierwszy element CFBundleLocalizations W info.plist jest zwracane

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-05 14:06:21

Próbowałem znaleźć odpowiednie rozwiązanie dla siebie. Kiedy używam Locale.preferredLanguages.first został zwrócony preferowany język z ustawień aplikacji.

Jeśli chcesz poznać język z ustawień urządzenia użytkownika, powinieneś użyć poniższego ciągu znaków:

Swift 3

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

Aby rozpakować i użyć, spójrz na poniższą linię:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-27 23:55:52

Aby uzyskać aktualny język urządzenia użytkownika, Użyj następującego kodu, który działał dla mnie.

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/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-27 12:51:10

Dla programistów MonoTouch C# użyj:

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

Uwaga: wiem, że to było pytanie na iOS, ale ponieważ jestem programistą MonoTouch, odpowiedź na tej stronie doprowadziła mnie we właściwym kierunku i pomyślałem, że podzielę się wynikami.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-20 18:27:21

W 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-06 07:40:36

Prosta funkcja 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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-05 00:06:39

Jeśli szukasz preferowanego kodu języka ("en", "de", "es"...w języku Swift jest to proste rozszerzenie:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-14 23:48:44

Jeśli chcesz dostać tylko język tutaj jest moja sugerowana odpowiedź:

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

W moim przypadku chciałem tylko język Locale nie region locale.

Wyjście: Jeśli twoim językiem lokalnym jest japoński, a regionem lokalnym jest Japonia, to:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-08 05:45:44

Dla Swift 3.0 poniższy kod może być użyty do odpowiedzi na twoje pytanie:

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-10 08:09:32

Według Apple Dokumentacja

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/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-16 11:32:44

Format dwóch liter. Apple stosuje standard 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-31 08:51:44

@Amir response in 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-30 20:06:00

Dla Swift 3:

NSLocale.preferredLanguages [0] As 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-04 16:31:35

Począwszy od iOS 9, Jeśli chcesz tylko kod języka bez kodu kraju, będziesz potrzebował tego rodzaju funkcji pomocniczej - ponieważ język będzie zawierał kod kraju.

// 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-24 00:07:21

Oczywiście rozwiązania polegające np. na

[[NSLocale preferredLanguages] objectAtIndex:0]

Zwykle działa poprawnie i zwraca bieżący język urządzenia.

Ale w niektórych przypadkach może to być mylące:

Jeśli aplikacja, w której chcesz uzyskać tę wartość, zmieniła już język, na przykład za pomocą tego rodzaju kodu:

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

W tym przypadku[nslocale preferredLanguages] w rzeczywistości zwraca preferowany zestaw języków (i używany) w danej aplikacji, a nie bieżące urządzenie język !

I... w tym przypadku jedynym sposobem na poprawne uzyskanie aktualnego języka urządzenia (a nie wcześniej ustawionego w aplikacji) jest najpierw wyczyszczenie klucza @"appleLanguages" w NSUserDefaults, jak to: {]}

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

Następnie, [nslocale preferredLanguages] zwraca teraz poprawną wartość.

Mam nadzieję, że to pomoże.
 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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-17 13:48:15

Zaktualizowana odpowiedź dla 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-26 11:51:01