作品鏈接:
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];
}