登录 |  注册
首页 >  移动开发 >  IOS开发入门教程笔记 >  iOS应用内购买

iOS应用内购买

iOS应用内购买(In-App Purchase, IAP)是苹果为开发者提供的一项服务,允许用户在下载并安装应用程序后,在应用程序内部购买额外的数字内容或功能升级。这些内容可以包括但不限于:

  1. 消耗型商品(Consumable):一次性使用且可以重复购买的商品,如游戏内的金币、道具、能量等。

  2. 非消耗型商品(Non-consumable):购买一次即可永久拥有的商品,例如解锁完整版应用、去广告特权或者某个特色主题。

  3. 订阅(Auto-Renewable Subscriptions):定期自动续费的服务,如新闻订阅、音乐/视频流媒体服务等。

  4. 非续订订阅(Non-Renewing Subscription):固定时长的订阅服务,到期后不会自动续费。


实例步骤

1.在 iTunes 连接中请确保拥有一个唯一的 App ID(unique App ID ),当创建捆绑的ID( bundle ID)应用程序更新时,代码会以相应的配置文件签名在Xcode上

2.创建新的应用程序和更新应用程序信息。你可以知道更多有关的,在苹果的 添加新的应用程序 文档中

3.在应用程序页的管理应用程序( Manage In-App Purchase)中,为app内付费添加新产品

4.确保设置的应用程序为的银行详细。需要将其设置为在应用程序内购买(In-App purchase)。此外在 iTunes 中使用管理用户(Manage Users)选项,创建一个测试用户帐户连接您的应用程序的页。

5.下一步是与处理代码和为我们在应用程序内购买创建有关的 UI。

6.创建一个单一的视图应用程序,并在 iTunes 中指定的标识符连接输入捆绑标识符

7.更新ViewController.xib 

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


注意: 需要修改你创建In-App Pur(应用内购买)的 kTutorialPointProductID 。通过修改fetchAvailableProducts产品标识符的 NSSet, 你可以添加多个产品。


上一篇: iOS整合iAD
下一篇: iOS地图开发
推荐文章
  • 在iOS开发中,要实现发送电子邮件的功能,可以使用MFMailComposeViewController类,这是Apple提供的一个内置框架——MessageUI的一部分。以下是在Swift中使用MFMailComposeViewController来发送邮件的基本步骤:实例步骤1、创建一个简单的V
  • iOS故事板(Storyboards)是Apple在iOS5中引入的一种可视化界面构建工具,它允许开发者在一个单一的文件中设计和管理整个应用程序的所有用户界面屏幕以及它们之间的导航关系。故事板通过InterfaceBuilder集成到Xcode开发环境中,为开发者提供了一种直观的方式来组织UI元素、
  • iOS自动布局(AutoLayout)是Apple在iOS6及以后版本引入的一种动态布局系统,用于处理用户界面元素在不同屏幕尺寸和方向下的自适应布局。通过自动布局,开发者可以创建灵活的、可伸缩的UI设计,确保应用在各种iPhone、iPad设备以及不同的屏幕旋转状态下都能保持良好的视觉效果和用户体验
  • ios(InternetworkingOperatingSystem-Cisco,缩写ios,也可写作IOS,区别于苹果系统iOS)iOS是由苹果公司(AppleInc.)开发的一种专有移动操作系统,它为苹果的多款移动设备提供用户界面和底层操作逻辑。最初随iPhone在2007年发布时被称为“iPh
  • 小程序中的组件也是由宿主环境提供的,开发者可以使用组件快速搭建出页面结构,官方把小程序里的组件分为了9大类,分别是视图容器基础内容表单组件导航组件媒体组件map地图组件canvas画布组件开放能力无障碍访问常见的视图容器类组件1.view普通视图区域类似于HTML中的div,是一个块级元素常用于实现
  • 一、下载并安装开发工具uniapp的开发工具为HbuilderX,下载地址为:去下载这里选择windows版本。windows版本下载完成之后会得到一个zip的压缩包文件,解压完成即可使用,是不需要安装的绿色版本。二、安装sass和scss插件打开HbuilderX,点击工具----插件安装,如图所
学习大纲