为应用内购买产品价格添加 UILabel



我在应用程序中设置了应用内购买,运行正常,但是我想将带有当地货币的"产品价格"调用到 viewController 上。

我在那里设置了 2 个使用 InAppBuy 代码的文件,如下所示:

InAppPurchaseSS.h

#import <Foundation/Foundation.h>
#import  "StoreKit/StoreKit.h"
#define kProductPurchasedNotification       @"ProductPurchased"
#define kProductPurchaseFailedNotification  @"ProductPurchaseFailed"
#define kProductPurchaseCancelledNotification  @"ProductPurchaseCancelled"
@interface InAppPurchaseSS : NSObject <SKProductsRequestDelegate,SKPaymentTransactionObserver,UIAlertViewDelegate>
{
    SKProductsRequest*   productsRequest;
    SKProduct *proUpgradeProduct;
    UIAlertView* waitingAlert;
    BOOL isTransactionOngoing;
    IBOutlet UILabel *productPriceLabel;
}
@property (retain) SKProductsRequest*   productsRequest;
@property (retain) NSArray * products;
@property (retain) SKProductsRequest *request;
@property (assign) BOOL isTransactionOngoing;
+ (InAppPurchaseSS *) sharedHelper;
-(id)init;
- (void)buyProductIdentifier:(NSString *)productIdentifier;
- (BOOL)canMakePurchases;
-(void)restoreInAppPurchase;
@end

InAppPurchaseSS.m

//
//  InAppPurchaseSS.m
//  Pharaonia
//
//  Created by iMac on 4/16/13.
//  Copyright (c) 2013 Apple. All rights reserved.
//
#import "InAppPurchaseSS.h"
#import "Reachability.h"
@implementation InAppPurchaseSS
@synthesize products;
@synthesize request;
@synthesize productsRequest;
@synthesize isTransactionOngoing;
static InAppPurchaseSS * _sharedHelper;
+ (InAppPurchaseSS *) sharedHelper {
    if (_sharedHelper != nil) {
        return _sharedHelper;
    }
    _sharedHelper = [[InAppPurchaseSS alloc] init];
    return _sharedHelper;
}
-(id)init {
    if( (self=[super init]))
    {
        isTransactionOngoing=NO;
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    }
    return self;
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSLog(@"Received products results...");
    self.products = response.products;
    self.request = nil;    
    NSLog(@"Number of product:%i : %@",[response.products count],response.products);
    NSArray *product = response.products;
    proUpgradeProduct = [product count] == 1 ? [[product firstObject] retain] : nil;
    if (proUpgradeProduct)
    {
        NSLog(@"Product title: %@" , proUpgradeProduct.localizedTitle);
        NSLog(@"Product description: %@" , proUpgradeProduct.localizedDescription);
        NSLog(@"Product price: %@" , proUpgradeProduct.price);
        NSLog(@"Product id: %@" , proUpgradeProduct.productIdentifier);
    }
    for (NSString *invalidProductId in response.invalidProductIdentifiers)
    {
        NSLog(@"Invalid product id: %@" , invalidProductId);
    }
    [productPriceLabel setText:[NSString stringWithFormat:
                                @"Product Price: %@",proUpgradeProduct.price]];


}

-(void)restoreInAppPurchase
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [reach currentReachabilityStatus];    
    if (netStatus == NotReachable) {        
        NSLog(@"No internet connection!");   
        [[[UIAlertView alloc] initWithTitle:@"No Internet"  message:@"Sorry, no internet connection found"   delegate:nil  cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];
        return;
    }
    waitingAlert = [[UIAlertView alloc] initWithTitle:@"Restoring..."  message:@"Please Wait...nn" delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [waitingAlert show];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}


- (void)buyProductIdentifier:(NSString *)productIdentifier {
    if ([productIdentifier isEqual: @""]) {
        NSLog(@"No IAP Product ID specified");
        return;
    }
    Reachability *reach = [Reachability reachabilityForInternetConnection]; 
    NetworkStatus netStatus = [reach currentReachabilityStatus];    
    if (netStatus == NotReachable) {        
        NSLog(@"No internet connection!");   
        [[[UIAlertView alloc] initWithTitle:@"No Internet" message:@"Sorry, no internet connection found"  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];
        return;
    } 
     isTransactionOngoing=YES;
    waitingAlert = [[UIAlertView alloc] initWithTitle:@"Purchasing..." message:@"Please Wait...nn" delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [waitingAlert show];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0) {
        SKMutablePayment *payment = [[SKMutablePayment alloc] init];
        payment.productIdentifier = productIdentifier;
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
    else {
        SKPayment *payment = [SKPayment paymentWithProductIdentifier:productIdentifier];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}

-(void)enableFeature
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"PurchaseSuccess"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error
{
    [waitingAlert dismissWithClickedButtonIndex:0 animated:YES];
    NSLog(@"Restore completed transaction failed");
}
- (BOOL)canMakePurchases
{
    return [SKPaymentQueue canMakePayments];
}
//
- (void)finishTransaction:(SKPaymentTransaction *)transaction wasSuccessful:(BOOL)wasSuccessful
{
    isTransactionOngoing=NO;
    [waitingAlert dismissWithClickedButtonIndex:0 animated:YES];
    // remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    if (wasSuccessful)
    {
        [self enableFeature];
        [[[UIAlertView alloc] initWithTitle:@"Congratulations!!" message:@"You have succesfully Purchases." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"successbuy" object:self];
    }
    else
    {
      [[[UIAlertView alloc] initWithTitle:@"Error!" message:transaction.error.localizedDescription  delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
        [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TransCancel" object: self];
    }
}

- (void)completeTransaction:(SKPaymentTransaction *)transaction
{
    NSLog(@"succesfull transaction");
    [self finishTransaction:transaction wasSuccessful:YES];
}
- (void)restoreTransaction:(SKPaymentTransaction *)transaction
{
    NSLog(@"transaction is restored");
    [self finishTransaction:transaction wasSuccessful:YES];
}

// called when a transaction has failed
- (void)failedTransaction:(SKPaymentTransaction *)transaction
{
    isTransactionOngoing=NO;
    NSLog(@"failed transaction called");
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        NSLog(@"Transaction failed called");
        NSLog(@"Transaction error: %@", transaction.error.localizedDescription);
        [self finishTransaction:transaction wasSuccessful:NO];
    }
    else
    {
        [waitingAlert dismissWithClickedButtonIndex:0 animated:YES];
        NSLog(@"user cancel transaction");
        // this is fine, the user just cancelled, so don’t notify
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TransCancel" object: self];
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    }
}

#pragma mark -
#pragma mark SKPaymentTransactionObserver methods
// called when the transaction status is updated
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    NSLog(@"transaction status updated");
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
                break;
            default:
                break;
        }
    }
} 
- (void) dealloc
{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
    [super dealloc];
}

@end

我设置了另一个视图控制器,我想在其中调用 UILabel 的本地产品价格。假设这称为SecondViewController。我知道在InAppPurchaseSS.m中,我有一个用于proUpgradeProduct.price的字段,但我需要将其称为带有本地货币的UI标签

这可能是我忽略的明显事情,但我希望得到一些帮助

谢谢

SKProduct 具有priceLocale属性和price属性,可用于为标签创建文本。

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

最新更新