2014-04-12 23 views
2

随着应用内购买,我希望本地货币符号明显适合用户本地货币。使用NSLocaleCurrencySymbol作为检测用户位置的主要来源是否安全?我的代码继承人部分:正确应用购买当地货币符号

  NSLocale *theLocale = [NSLocale currentLocale]; 
    NSString *symbol = [theLocale objectForKey:NSLocaleCurrencySymbol]; 
    NSString *cost = [NSString stringWithFormat:@"%@",product.price]; 

默认情况下是正确的区域格式自动当用户购买iOS设备的每个设备上的国际设置完成?

回答

7

您想使用NSNumberFormatter

Objective-C的

NSNumberFormatter *formatter = [NSNumberFormatter new]; 
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle]; 
[formatter setLocale:product.priceLocale]; 
NSString *cost = [formatter stringFromNumber:product.price]; 

斯威夫特

let formatter = NSNumberFormatter() 
formatter.numberStyle = .CurrencyStyle 
formatter.locale = product.priceLocale 
let cost = formatter.stringFromNumber(product.price) 

这将然后用正确的decimalisation,分离器格式使用的货币和货币符号。

+0

是否有检测,因为如果我改变我的iphone国际设置的方式我在应用程序内购买送花儿给人表明英国(£)货币符号? – pete

+0

它使用'SKProduct'的语言环境(因此是货币)而不是设备,因此您实际上正在测试它:) – Rich

+0

好的,那么是否有测试货币符号的方法? – pete

2

你并不需要做的是,SKProduct带有一个本地用户存储,您可以使用 -

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; 
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; 
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; 
[numberFormatter setLocale:product.priceLocale]; 
NSString *formattedString = [numberFormatter stringFromNumber:product.price]; 

看这里 -

Apple Docs

+0

谢谢你的帮助 - 但无论区域格式,我设置我的iPhone总是出来作为我的本地货币(英镑)。例如,在我的iPhone上,如果我将区域格式设置为美国 - 当我测试应用程序购买时,它仍然表示英镑不是美元? – pete

+1

是的,因为格式SKProduct由用户登录的App Store国家设置,如果您尝试自己设置本地,则会向用户显示错误的价格。您应该测试的方式是在其他应用商店中打开测试帐户,然后检查货币 – shannoga

2

在迅速

var currency_format = NSNumberFormatter() 
currency_format.numberStyle = NSNumberFormatterStyle.CurrencyStyle 
currency_format.locale = validProduct.priceLocale 
mylabel.text = currency_format.stringFromNumber(validProduct.price) 
2

已更新至Swift 3.0并作为S的扩展KProduct:

import StoreKit 

extension SKProduct { 
    func getLocalizedPrice()->String{ 
     let formatter = NumberFormatter() 
     formatter.numberStyle = .currency 
     formatter.locale = self.priceLocale 
     return formatter.string(from: self.price) 
     } 
} 
+0

好的答案请记住格式化程序的'string(from:Number)'方法返回一个可选项,所以你需要指定'String?'作为返回类型或者在返回之前强制解包。 –