NSLocale和国家名称

43

我使用了下面的代码来获取iPhone所属的国家:

NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];
NSString *country = [locale displayNameForKey: NSLocaleCountryCode value: countryCode];

我希望始终以英语获取国家名称,但如果iPhone设置为其他语言,则会返回该语言的国家名称...


4
请注意,语言和地区均可由用户配置。例如,一个以英语为母语的用户从未离开过美国,但碰巧正在学习意大利语,可能会将其iPhone的语言和地区更改为意大利。而将手机设置为美式英语的人则可以出国旅行。如果您真的想找出手机当前所在的国家,请使用地理定位功能。 - Jeremy W. Sherman
@JeremyW.Sherman:同意。使用locale来确定如何本地化您的内容,而不是确定用户所在的位置。 - Alan
2个回答

105

查询英文环境的displayName

像这样:

NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];

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

NSString *country = [usLocale displayNameForKey: NSLocaleCountryCode value: countryCode];

13

这里是一段关于在SWIFT中获取可用NSLocale对象信息的代码,只需将代码放入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()

您会收到这种类型的信息(示例):
您会收到这种类型的信息(示例):

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接