如何在SKPayment中访问产品的价格?

fav*_*avo 40 iphone xcode in-app-purchase

我正在为iPhone应用程序购买应用内购买.

我想在UILabel中以用户本地货币显示价格.为此我需要变量中的价格和货币.

如何使用SKPayment获得包括货币在内的价格?(如果SKPayment正确用于此用途.)

我使用以下方法实例化产品:

SKPayment *payment = [SKPayment paymentWithProductIdentifier:@"Identifier"];
Run Code Online (Sandbox Code Playgroud)

提前感谢您的反馈!

gid*_*gid 119

使用NSLocaleCurrencySymbol + price.stringValue有一个问题:它不能处理不同语言环境的特殊性,例如.他们是否将货币符号放在前面.例如,挪威,丹麦,瑞典和瑞士都将货币放在后面.17.00Kr.此外,大多数(?)欧洲国家使用','而不是'.' 小数,例如."2,99€"而不是"€2.99".

更好的计划是使用NSNumberFormatter.正如Ed所说,SKProduct返回的"priceLocale"是关键.它为NSNumberFormatter提供了正确格式化价格的智能.

通过使用Objective-C类别向SKProduct添加新属性,您还可以更轻松地实现此目的.将以下两个文件添加到项目中:


SKProduct + priceAsString.h:

#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>

@interface SKProduct (priceAsString)
@property (nonatomic, readonly) NSString *priceAsString;
@end
Run Code Online (Sandbox Code Playgroud)

SKProduct + priceAsString.m:

#import "SKProduct+priceAsString.h"

@implementation SKProduct (priceAsString)

- (NSString *) priceAsString
{
  NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
  [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
  [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
  [formatter setLocale:[self priceLocale]];

  NSString *str = [formatter stringFromNumber:[self price]];
  [formatter release];
  return str;
}

@end
Run Code Online (Sandbox Code Playgroud)

然后,#import "SKProduct+priceAsString.h"在您的代码中,您应该只能product.priceAsString在代码中使用.

  • 知道如何用不同的货币测试吗? (4认同)

Ed *_*rty 9

确定任何信息的正确方法是使用一个SKProduct对象,该SKProductResponse对象是在调用- (void) start初始化后从返回给委托的对象中检索的SKProductsRequest.像这样的东西:

SKProductsRequest *req = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:@"Identifier"]];
req.delegate = self;
[req start];

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse: (SKProductsResponse *)response {
    [request autorelease];
    if (response.products.count) {
        SKProduct *product = [response.products objectAtIndex:0];
        NSLocale *priceLocale = product.priceLocale;
        NSDecimalNumber *price = product.price;
        NSString *description = product.localizedDescription;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!像这样使用它:myLabel.text = [NSString stringWithFormat:NSLocalizedString(@"bla cost is%@%@",nil),[priceLocale objectForKey:NSLocaleCurrencySymbol],[price stringValue]]; (5认同)