I have seen this answered in objective-C, but I don't know how to convert to swift.
My app receives the public information of a user from Facebook, and I need to convert the locale into the country name.
FBRequestConnection.startForMeWithCompletionHandler({
connection, result, error in
user["locale"] = result["locale"]
user["email"] = result["email"]
user.save()
println(result.locale)
})
For example, for a French user, the code sends "Optional(fr_FR)" to the log. However I need it to just send the country name. According to localeplanet.com, the display name of "fr_FR" is "French (France)". So in the log all I want is "France".
Working off of this SO question, I've whipped up a Swift translation. Try this:
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)
}
Updated for 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)
}
}