iOS - 应用内购买



应用内购买用于购买应用程序的附加内容或升级功能。

涉及的步骤

步骤 1 - 在 iTunes Connect 中,确保您拥有一个唯一的 App ID,并且当我们创建应用程序更新时,使用bundle ID 和 Xcode 中的代码签名以及相应的配置文件。

步骤 2 - 创建一个新应用程序并更新应用程序信息。您可以在 Apple 的添加新应用文档中了解更多信息。

步骤 3 - 在应用程序页面中的管理应用内购买中为应用内购买添加新产品。

步骤 4 - 确保您设置了应用程序的银行详细信息。这需要为应用内购买设置才能工作。此外,使用应用的 iTunes Connect 页面中的管理用户选项创建一个测试用户帐户。

步骤 5 - 下一步与处理代码和为我们的应用内购买创建 UI 相关。

步骤 6 - 创建一个单视图应用程序,并输入在 iTunes Connect 中指定的 bundle identifier。

步骤 7 - 更新ViewController.xib,如下所示 -

iOS Tutorial

步骤 8 - 为三个标签和按钮创建IBOutlets,分别命名为 productTitleLabel、productDescriptionLabel、productPriceLabel 和 purchaseButton。

步骤 9 - 选择您的项目文件,然后选择目标,然后添加StoreKit.framework

步骤 10 - 更新ViewController.h,如下所示 -

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

@interface ViewController : UIViewController<
SKProductsRequestDelegate,SKPaymentTransactionObserver> {
   SKProductsRequest *productsRequest;
   NSArray *validProducts;
   UIActivityIndicatorView *activityIndicatorView;
   IBOutlet UILabel *productTitleLabel;
   IBOutlet UILabel *productDescriptionLabel;
   IBOutlet UILabel *productPriceLabel;
   IBOutlet UIButton *purchaseButton;
}

- (void)fetchAvailableProducts;
- (BOOL)canMakePurchases;
- (void)purchaseMyProduct:(SKProduct*)product;
- (IBAction)purchase:(id)sender;

@end

步骤 11 - 更新ViewController.m,如下所示 -

#import "ViewController.h"
#define kTutorialPointProductID 
@"com.tutorialPoints.testApp.testProduct"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   
   // Adding activity indicator
   activityIndicatorView = [[UIActivityIndicatorView alloc]
   initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
   activityIndicatorView.center = self.view.center;
   [activityIndicatorView hidesWhenStopped];
   [self.view addSubview:activityIndicatorView];
   [activityIndicatorView startAnimating];
   
   //Hide purchase button initially
   purchaseButton.hidden = YES;
   [self fetchAvailableProducts];
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
}

-(void)fetchAvailableProducts {
   NSSet *productIdentifiers = [NSSet 
   setWithObjects:kTutorialPointProductID,nil];
   productsRequest = [[SKProductsRequest alloc] 
   initWithProductIdentifiers:productIdentifiers];
   productsRequest.delegate = self;
   [productsRequest start];
}

- (BOOL)canMakePurchases {
   return [SKPaymentQueue canMakePayments];
}

- (void)purchaseMyProduct:(SKProduct*)product {
   if ([self canMakePurchases]) {
      SKPayment *payment = [SKPayment paymentWithProduct:product];
      [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
      [[SKPaymentQueue defaultQueue] addPayment:payment];
   } else {
      UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
      @"Purchases are disabled in your device" message:nil delegate:
      self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
      [alertView show];
   }
}
-(IBAction)purchase:(id)sender {
   [self purchaseMyProduct:[validProducts objectAtIndex:0]];
   purchaseButton.enabled = NO; 
}

#pragma mark StoreKit Delegate

-(void)paymentQueue:(SKPaymentQueue *)queue 
updatedTransactions:(NSArray *)transactions {
   for (SKPaymentTransaction *transaction in transactions) {
      switch (transaction.transactionState) {
         case SKPaymentTransactionStatePurchasing:
            NSLog(@"Purchasing");
         break;
         
         case SKPaymentTransactionStatePurchased:
            if ([transaction.payment.productIdentifier 
            isEqualToString:kTutorialPointProductID]) {
               NSLog(@"Purchased ");
               UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
               @"Purchase is completed succesfully" message:nil delegate:
               self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
               [alertView show];
            }
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
         break;
            
         case SKPaymentTransactionStateRestored:
            NSLog(@"Restored ");
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
         break;
            
         case SKPaymentTransactionStateFailed:
            NSLog(@"Purchase failed ");
         break
         default:
         break;
      }
   }
}

-(void)productsRequest:(SKProductsRequest *)request 
didReceiveResponse:(SKProductsResponse *)response {
   SKProduct *validProduct = nil;
   int count = [response.products count];
   
   if (count>0) {
      validProducts = response.products;
      validProduct = [response.products objectAtIndex:0];
      
      if ([validProduct.productIdentifier 
         isEqualToString:kTutorialPointProductID]) {
         [productTitleLabel setText:[NSString stringWithFormat:
            @"Product Title: %@",validProduct.localizedTitle]];
         [productDescriptionLabel setText:[NSString stringWithFormat:
            @"Product Desc: %@",validProduct.localizedDescription]];
         [productPriceLabel setText:[NSString stringWithFormat:
            @"Product Price: %@",validProduct.price]];
      }
   } else {
      UIAlertView *tmp = [[UIAlertView alloc]
         initWithTitle:@"Not Available"
         message:@"No products to purchase"
         delegate:self
         cancelButtonTitle:nil
         otherButtonTitles:@"Ok", nil];
         [tmp show];
   }
   
   [activityIndicatorView stopAnimating];
   purchaseButton.hidden = NO;
}
@end

注意

您必须将 kTutorialPointProductID 更新为为应用内购买创建的产品 ID。您可以通过更新 fetchAvailableProducts 中的 productIdentifiers 的 NSSet 来添加多个产品。类似地,处理您添加的产品 ID 的购买相关操作。

输出

当我们运行应用程序时,我们将获得以下输出 -

iOS Tutorial

确保您已在设置屏幕中注销帐户。点击“开始购买”后,选择“使用现有 Apple ID”。输入您的有效测试帐户用户名和密码。几秒钟后,您将看到以下警报。

iOS Tutorial

成功购买产品后,您将收到以下警报。您可以看到更新应用程序功能的相关代码,我们在此显示此警报。

iOS Tutorial
广告