首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSLocale到国家名称

NSLocale到国家名称
EN

Stack Overflow用户
提问于 2014-12-15 18:20:07
回答 1查看 5.4K关注 0票数 1

我已经在目标C中看到了这个答案,但我不知道如何转换为斯威夫特。

我的应用程序从Facebook接收用户的公共信息,我需要将地区转换成国家名称。

代码语言:javascript
复制
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“的显示名是”法语(法国)“。所以在日志里我只想要“法国”。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-15 18:50:36

this SO question工作之后,我做了一个迅速的翻译。试试这个:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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)
    }
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27490494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档