在Swift中获取本地货币

29

我正在为多个国家设置应用内购买商店。如何确定需要以美元、欧元等货币显示价格?我认为这与localeIdentifier有关,但我不确定该如何处理。

3个回答

78

你可以使用(NS)Locale获取货币符号和代码。

Swift 1 和 2

let locale = NSLocale.currentLocale()
let currencySymbol = locale.objectForKey(NSLocaleCurrencySymbol)!
let currencyCode = locale.objectForKey(NSLocaleCurrencyCode)!

Swift 3

let locale = Locale.current()
let currencySymbol = locale.object(forKey: .currencySymbol)!
let currencyCode = locale.object(forKey: .currencyCode)!

Swift 3.1+

:Swift 3.1及以上版本。
let locale = Locale.current
let currencySymbol = locale.currencySymbol!
let currencyCode = locale.currencyCode!

这与用户地区格式设置相关,在 iOSmacOS 上都适用。


使用Xcode beta 4(Swift 3)时,我遇到了错误:“类型'Locale'的值没有成员'object'”。 - blwinters
@blwinters 我认为 Swift 3 的等效代码是 Locale.current.regionCode。 - bolnad
@blwinters 在测试版阶段,语法可能会随时更改。请在相应的Xcode版本中阅读Locale文档。 - vadian
@vadian 好的,我在这里看到(https://developer.apple.com/reference/foundation/nslocale)currencyCode现在是Locale的一个属性,object(forKey:)不再可用,或者至少没有标记为“Beta”。 - blwinters
同时 Locale.current() 变成了 Locale.current。 :) - HAS
1
@HAS 谢谢 :-) - vadian

9

针对Swift3

//User region setting return
let locale = Locale.current //NSLocale.current

//Returns true if the locale uses the metric system (Note: Only three countries do not use the metric system: the US, Liberia and Myanmar.)
let isMetric = locale.usesMetricSystem

//Returns the currency code of the locale. For example, for “zh-Hant-HK”, returns “HKD”.  
let currencyCode  = locale.currencyCode

//Returns the currency symbol of the locale. For example, for “zh-Hant-HK”, returns “HK$”.
let currencySymbol = locale.currencySymbol

1

适用于iOS 16+

//Returns the user's current locale
let locale = Locale.current

//Returns the local currency's symbol
//Ex: $
let currencySymbol = locale.currencySymbol!

//Returns the currency code of the locale. Returns nil if the data isn't available
//Ex: USD
let currencyCode = locale.currency!.identifier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接