[ios] iOS에서 현재 장치 언어를 가져 오십니까?

장치 UI가 사용하는 현재 언어를 보여주고 싶습니다. 어떤 코드를 사용해야합니까?

나는 이것을 NSString완전히 철자 된 형식 으로 원합니다 . (@ “en_US”아님)

편집 : 새로운 iOS 릴리스로 답변이 발전함에 따라 여기에 많은 도움이되는 의견이 있습니다.



답변

제공된 솔루션은 실제로 현재 선택된 언어가 아닌 장치의 현재 영역을 반환합니다. 이들은 종종 하나이며 동일합니다. 그러나 내가 북미에 있고 언어를 일본어로 설정하면 내 지역은 여전히 ​​영어 (미국)가됩니다. 현재 선택된 언어를 검색하려면 다음을 수행하십시오.

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

현재 선택된 언어에 대한 두 글자 코드를 반환합니다. 영어의 경우 “en”, 스페인어의 경우 “es”, 독일어의 경우 “de”등이 있습니다. 자세한 예는 다음 Wikipedia 항목 (특히 639-1 열)을 참조하십시오.

ISO 639-1 코드 목록

그런 다음 두 문자 코드를 표시하려는 문자열로 변환하는 것이 간단합니다. “en”이면 “English”를 표시하십시오.

이것이 지역과 현재 선택된 언어를 구별하려는 사람에게 도움이되기를 바랍니다.

편집하다

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

앱 언어에 관심이있는 사람들은 @mindvision의 답변을 살펴보십시오.


답변

선택한 답변은 현재 장치 언어를 반환하지만 앱에서 사용 된 실제 언어는 반환하지 않습니다. 앱에서 사용자가 선호하는 언어로 현지화를 제공하지 않으면 사용자가 선호하는 순서대로 정렬 된 첫 번째 현지화가 사용됩니다.

현지화에서 선택한 현재 언어를 찾으려면

[[NSBundle mainBundle] preferredLocalizations];

예:

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

빠른:

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


답변

iOS 9 용 솔루션 :

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

언어 = “en-US”

NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];

languageDic은 필요한 구성 요소를 갖습니다

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

countryCode = “미국”

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

languageCode = “en”


답변

이것은 아마도 당신이 원하는 것을 줄 것입니다 :

NSLocale *locale = [NSLocale currentLocale];

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

언어 자체의 언어 이름이 표시됩니다. 예를 들면 다음과 같습니다.

Français (France)
English (United States)


답변

경고허용되는 답변과 다른 답변은 모두 선호 언어가 장치 언어 이외의 다른 언어 일 수 있다는 점을 고려하지 않습니다 .

장치 언어는 운영 체제 요소와 애플의 애플 리케이션을 제시하는 언어입니다.

선호하는 언어는 사용자가 애플 만 번역의 제한된 집합을 제공합니다. 현지화 애플 리케이션을하고 싶은 언어입니다. 선호하는 언어가 Apple이 앱을 번역 한 언어 인 경우 장치 언어이기도합니다. 그러나 사용자가 Apple에서 번역을 제공하지 않는 언어를 선호하는 경우 기기와 선호하는 언어가 일치하지 않습니다 . 장치 언어는 기본 언어 목록에서 첫 번째 위치에 있지 않습니다.

다음 함수는 기본 언어 목록을 살펴보고 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
}

선호하는 언어 목록이 다음과 같은 경우에 작동합니다.

  1. 아프리칸스어 (iOS는 아프리칸스어로 번역되지 않음)
  2. 스페인어 (장치 언어)

선호하는 언어 목록이 될 수 편집 : 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)
    }
} 


답변

나는 이것을 사용한다

    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


답변

같은 번역 언어 코드 ko 페이지영어 (미국) a는의 기능이 내장되어 NSLocaleNSLocale당신의 언어 코드를 얻을 경우 상관하지 않는다. 따라서 받아 들여진 대답에서 알 수 있듯이 자신의 번역을 구현할 이유가 없습니다.

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

인쇄 : 영어, 독일어, 스웨덴어