NSLocale和国家/地区名称

问题描述

| 我使用此代码获取iPhone所属的国家/地区:
NSLocale *locale = [NSLocale currentLocale];
Nsstring *countryCode = [locale objectForKey: NSLocaleCountryCode];
Nsstring *country = [locale displayNameForKey: NSLocaleCountryCode value: countryCode];
我想始终以英语获取国家名称,但是如果iPhone使用其他任何语言,它将以该语言返回国家名称...     

解决方法

        在英语语言环境中查询displayName 像这样:
NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@\"en_US\"];

NSString *country = [usLocale displayNameForKey: NSLocaleCountryCode value: countryCode];
    ,        以下是一些代码,用于获取有关SWIFT中可用的NSLocale-Objects的一些信息,只需将代码放入Playground:
func printInEnglish() {

    // get all available Identifiers
    let allLocaleIdentifiers : Array<String> = NSLocale.availableLocaleIdentifiers as Array<String>

    // init an english NSLocale to get the english name of all NSLocale-Objects
    let englishLocale : NSLocale = NSLocale.init(localeIdentifier :  \"en_US\")

    // enumerate all available Identifiers
    for anyLocaleID in allLocaleIdentifiers {

        // get the english name
        var theEnglishName : String? = englishLocale.displayName(forKey: NSLocale.Key.identifier,value: anyLocaleID)
        if theEnglishName == nil {theEnglishName = \"no english name available\"}

        // create a NSLocale-Object
        let anyLocale : NSLocale  = NSLocale.init(localeIdentifier : anyLocaleID)

        // ask for CurrencyCode,CurrencySymbol and CountryCode,... of the created NSLocale-Object
        var theCurrencyCode : String? = anyLocale.object(forKey: NSLocale.Key.currencyCode) as? String
        if theCurrencyCode == nil {theCurrencyCode = \"no Currency Code available\"}

        var theCurrencySymbol : String? = anyLocale.object(forKey: NSLocale.Key.currencySymbol) as? String
        if theCurrencySymbol == nil {theCurrencySymbol = \"no currency symbol available\"}

        var theCountryCode : String? = anyLocale.object(forKey: NSLocale.Key.countryCode) as? String
        if theCountryCode == nil {theCountryCode = \"no country code available\"}

        var theLanguageCode : String? = anyLocale.object(forKey: NSLocale.Key.languageCode) as? String
        if theLanguageCode == nil {theLanguageCode = \"no language code available\"}

        // print the result -> see the result in LoggingArea of xCode
        print(\"Identifier   : \\(anyLocaleID)\\nName         : \\(theEnglishName!)\\nCurrencyCode : \\(theCurrencyCode!)\\nSymbol       : \\(theCurrencySymbol!)\\nLanguageCode : \\(theLanguageCode!)\\nCountryCode  : \\(theCountryCode!)\\n----------------------------\")
    }
}

printInEnglish()
您会获得以下信息(示例):