NSLocale到国家/地区名称

时间:2014-12-15 18:20:08

标签: ios facebook swift locale nslocale

我已经在Objective-C中看到了这个问题,但我不知道如何转换为swift。

我的应用从Facebook收到用户的公开信息,我需要将语言环境转换为国家/地区名称。

FBRequestConnection.startForMeWithCompletionHandler({
            connection, result, error in    
            user["locale"] = result["locale"]
            user["email"] = result["email"]
            user.save()

            println(result.locale)


        })

例如,对于法国用户,代码发送"可选(fr_FR)"到日志。但是我需要它才能发送国家名称。根据localeplanet.com,显示名称为" fr_FR"是"法语(法国)"。因此,在日志中我想要的只是" France"。

1 个答案:

答案 0 :(得分:9)

this SO question工作之后,我发了一个Swift翻译。试试这个:

let locale: NSLocale = NSLocale(localeIdentifier: result.locale!)
let countryCode = locale.objectForKey(NSLocaleCountryCode) as String
var country: String? = locale.displayNameForKey(NSLocaleCountryCode, value: countryCode)

// According to the docs, "Not all locale property keys
// have values with display name values" (thus why the 
// "country" variable's an optional). But if this one
// does have a display name value, you can print it like so.
if let foundCounty = country {
    print(foundCounty)
}

针对Swift 4进行了更新:

FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"locale"]).start { (connection, result, error) in

    guard let resultDictionary = result as? [String:Any], 
          let localeIdentifier = resultDictionary["locale"] as? String else {
        return
    }

    let locale: NSLocale = NSLocale(localeIdentifier: localeIdentifier)

    if let countryCode = locale.object(forKey: NSLocale.Key.countryCode) as? String,
       let country = locale.displayName(forKey: NSLocale.Key.countryCode, value: countryCode) {
        print(country)
    }
}