ios - NSLocale 到国家名称

标签 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)


        })

例如,对于法国用户,代码将“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)
    }
}

关于ios - NSLocale 到国家名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490494/

相关文章:

authentication - 通过 OpenID、Oauth 或 Facebook Connect 进行身份验证后重定向回页面

ios - 从应用程序设置中的应用程序注销

快速核心数据: save images from camera

ios - 第三方框架与私有(private)框架?

ios - 在IOS中自定义UINavigationBar而不使用UINavigationController设置背景图像不起作用

facebook - 如何修复 Facebook 循环重定向?

ios - Collection View 内的 TableView

ios - 遍历来自 Alamofire 的 JSON 响应

ios - 如何使用 SDK 版本 5.0 部署 xamarin ios 应用程序以在 visual studio 2013 中使用旧主题(不是 iOS 7 主题)

facebook - 带有计数的紧凑型 Facebook 共享按钮?