iOS中app內購方法

作品鏈接:
http://www.lxweimin.com/users/1e0f5e6f73f6/top_articles

1.請求所有可賣的商品

1.導入第三方框架
2.遵守協議<SKProductsRequestDelegate>

#import <StoreKit/StoreKit.h>

- (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<SKPaymentTransaction *> *)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];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一種新的協議。它實...
    香橙柚子閱讀 24,113評論 8 183
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,460評論 25 708
  • 你是不是這種人呢?平時面對任何人都你可以侃侃而談,然而遇到了喜歡的女生。你整個人就處于一種懵逼的狀態,不知道如何和...
    公子義閱讀 1,810評論 0 3
  • 1、 每個男孩都有一個英雄夢,夢想著自己有一天擁有了超能力,然后做出種種英勇壯舉,解救萬民,國家,甚至地球于危難之...
    牧云則哉閱讀 927評論 0 1
  • 背離的背后是股價速度的變化, 在上升過程中,上升速度放緩,代表買盤力量的衰竭,通常導致頂部背離出現 在下降過程中,...
    后80閱讀 393評論 0 0