我在 objective-C 中看到了这个答案,但我不知道如何转换为 swift。
我的应用程序从 Facebook 接收用户的公开信息,我需要将区域设置转换为国家/地区名称。
FBRequestConnection.startForMeWithCompletionHandler({
connection, result, error in
user["locale"] = result["locale"]
user["email"] = result["email"]
user.save()
println(result.locale)
})
例如,对于法国用户,代码将“Optional(fr_FR)”发送到日志。但是我需要它来发送国家名称。根据 localeplanet.com,“fr_FR”的显示名称是“French(法国)”。所以在日志中我想要的只是“法国”。
正在处理 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)
}
}