iOS中app内购方法

作品链接:
http://www.jianshu.com/users/1e0f5e6f73f6/top_articles

1.请求所有可卖的商品

1.导入第三方框架
2.遵守协议

#import 

- (void)requestProducts
{
    // 1.拿到所有想卖商品的ProductID
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"iapdemo.plist" ofType:nil];
    NSArray *products = [NSArray arrayWithContentsOfFile:filePath];
    NSArray *productIDs = [products valueForKeyPath:@"productId"];
    
    // 2.向苹果发送请求,请求所有可买的商品
    //   2.1.创建请求对象
    NSSet *sets = [NSSet setWithArray:productIDs];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:sets];
    
    //   2.2.设置代理
    request.delegate = self;
    
    //   2.3.开始请求
    [request start];
}

2.实现SKProductsRequest的代理方法

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSLog(@"%ld",response.products.count);
    // 1.对数组中对象进行排序(根据商品价格排序)
    NSArray *products = [response.products sortedArrayWithOptions:NSSortStable usingComparator:^NSComparisonResult(SKProduct *obj1, SKProduct *obj2) {
        return [obj1.price compare:obj2.price];
    }];
    
    // 2.保存数组
    self.products = products;
    
    // 3.刷新表格
    [self.tableView reloadData];
}

3.实现tableView的数据源和代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.products.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.创建cell
    static NSString *ID = @"productCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    // 2.给cell设置是数据
    SKProduct *product = self.products[indexPath.row];
    cell.textLabel.text = product.localizedTitle;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"价格:%@",product.price];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.取出用户选中商品
    SKProduct *product = self.products[indexPath.row];
    // 2.购买该商品
    [self buyProduct:product];
}

4.购买商品

- (void)buyProduct:(SKProduct *)product
{
    // 1.创建票据
    SKPayment *payment = [SKPayment paymentWithProduct:product];
    // 2.将票据加入到交易队列
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

5.添加观察者,监听用户是否付钱成功

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
    注意: 需遵守 SKPaymentTransactionObserver 协议
#pragma mark - 实现观察者协议中的方法,来监听交易的变化
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    /*
     SKPaymentTransactionStatePurchasing,    正在购买
     SKPaymentTransactionStatePurchased,     购买成功
     SKPaymentTransactionStateFailed,        购买失败
     SKPaymentTransactionStateRestored,      恢复购买
     SKPaymentTransactionStateDeferred       最终状态未决定,交易依然在队列中
     */
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"正在购买商品");
                break;
                
            case SKPaymentTransactionStatePurchased:
                NSLog(@"购买成功.给用户对应商品");
                // 交易移除
                [queue finishTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateFailed:
                NSLog(@"购买失败");
                [queue finishTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateRestored:
                NSLog(@"恢复购买");
                [queue finishTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateDeferred:
                NSLog(@"未决定状态");
                break;
            default:
                break;
        }
    }
}

6.加载及恢复购买

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 请求所有可卖的商品
    [self requestProducts];
    
    // 添加导航栏右侧的按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"恢复" style:UIBarButtonItemStyleDone target:self action:@selector(restoreProduct)];
}

// 恢复购买
- (void)restoreProduct
{
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

你可能感兴趣的:(iOS中app内购方法)