参考:
http://www.raywenderlich.com/105365
StoreKit提供了关于IAP的所有的类:
在项目中使用得最多的几个类和次数如下:
SKPayment - 2 , SKPaymentQueue - 16, SKPaymentTransaction - 12
SKProduct - 12, SKProductsRequest - 5
我们只要围绕这几个类入手即可。
SKProductsRequest类,顾名思义了,从IAP服务器请求product信息:
最重要的方法:
- (instancetype)initWithProductIdentifiers:(NSSet<NSString *> *)productIdentifiers NS_AVAILABLE_IOS(3_0);
简单使用:
- (void)requestProducts
{
self.request = [[SKProductsRequest alloc] initWithProductIdentifiers:_productIdentifiers];
_request.delegate = self;
[_request start];
}
- (void)payProductID:(NSString *)productID completionHandler:(PayHandler)handler
{
self.payHandle = handler;
//查找productID的商品是否在缓存里
SKProduct *cacheProduct = [self findProductWithProductID:productID];
if (cacheProduct == nil)
{
NSSet *productSet = [NSSet setWithObject:productID];
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:productSet];
[request setDelegate:self];
[request start];
}
else
{
[self payProduct:cacheProduct];
}
}
另外相应地存在一个委托:
@property(nonatomic, assign, nullable) id <SKProductsRequestDelegate> delegate NS_AVAILABLE_IOS(3_0);
完整的协议:
@protocol SKProductsRequestDelegate <SKRequestDelegate>
@required
// Sent immediately before -requestDidFinish:
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response NS_AVAILABLE_IOS(3_0);
@end
可以看到SKProductsRequestDelegate 是派生 SKRequestDelegate的:
@protocol SKRequestDelegate <NSObject>
@optional
- (void)requestDidFinish:(SKRequest *)request NS_AVAILABLE_IOS(3_0);
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error NS_AVAILABLE_IOS(3_0);
@end
它有请求失败的回调。
简单使用:
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSLog(@"Received products results...");
self.products = response.products;
self.request = nil;
[[NSNotificationCenter defaultCenter] postNotificationName:kProductsLoadedNotification object:_products];
}
很显然就是处理回调的product结果用的,可以适当加个通知
SKProduct
这个类就是你在iTunes Connect里面设置的产品类,是通过SKProductsResponse返回的,而SKProductsResponse就是前面的协议回调可以得到。
抽出重要的两个属性,分别是价格和描述符,重重要!我们做三方的统计的时候,常常就是用这两个变量来做标准参数的!@property(nonatomic, readonly) NSDecimalNumber *price NS_AVAILABLE_IOS(3_0);
@property(nonatomic, readonly) NSString *productIdentifier NS_AVAILABLE_IOS(3_0);
简单使用,来生成payment类,并将支付添加到支付队列里
- (void)payProduct:(SKProduct *)product
{
SKPayment *payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
SKPayment
@property(nonatomic, copy, readonly) NSString *productIdentifier NS_AVAILABLE_IOS(3_0);
+ (instancetype)paymentWithProduct:(SKProduct *)product NS_AVAILABLE_IOS(3_0);
+ (id)paymentWithProductIdentifier:(NSString *)identifier NS_DEPRECATED_IOS(3_0, 5_0, "Use +paymentWithProduct: after fetching the available products using SKProductsRequest");
简单的使用如上,可以生成支付队列
SKPaymentQueue
下一篇重点讲