编辑后的答案更完整:
在您的 ViewController.h 文件中应该有
@interface ViewController : UIViewController <SKProductsRequestDelegate> {
NSArray *allProducts;
}
然后在 ViewController.m 例如。在viewDidload
:
-(void) viewDidload {
[super viewDidLoad];
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:@"xxxx1",@"xxxx2",nil]];
request.delegate=self;
[request start];
}
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
allProducts = response.products;
NSLog(@"Fetched %d products", allProducts.count);
}
然后它可以这样使用:
-(NSString*) getPriceForProductWithID:(NSString*)productID{
if(allProducts.count < 1) {
NSLog(@"Did not fetch products yet");
}
else {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
for(SKProduct * product in allProducts) {
if([product.productIdentifier isEqualToString:productID])
{
[numberFormatter setLocale:product.priceLocale];
NSString *priceString= [numberFormatter stringFromNumber:product.price];
NSLog(@"Product with ID: %@ has price: %@",product.productIdentifier, priceString);
return priceString;
}
}
}
return nil;
}