NSLocale到国家/地区名称

Tim*_*ing 1 locale facebook ios nslocale swift

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

我的应用程序从Facebook接收用户的公共信息,我需要将语言环境转换为国家/地区名称.

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

            println(result.locale)


        })
Run Code Online (Sandbox Code Playgroud)

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

Lyn*_*ott 10

解决这个问题,我已经掀起了一个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)
}
Run Code Online (Sandbox Code Playgroud)

针对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)
    }
}
Run Code Online (Sandbox Code Playgroud)