定格 2020-04-07
刚刚做了内购, 记录一下
这里直接上代码, 至于写代码之前的一些设置工作参考以下文章:
http://www.jianshu.com/p/690a7c68664e
http://www.jianshu.com/p/86ac7d3b593a
需要注意的是:
// // IAPManager.m // SpeakEnglish // // Created by Daniel on 16/6/8. // Copyright © 2016年 Daniel. All rights reserved. // #import "IAPManager.h" #import <StoreKit/StoreKit.h> @interface IAPManager ()<SKPaymentTransactionObserver, SKProductsRequestDelegate> // 所有商品 @property (nonatomic, strong)NSArray *products; @property (nonatomic, strong)SKProductsRequest *request; @end static IAPManager *manager = nil; @implementation IAPManager + (instancetype)shareIAPManager { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ manager = [self new]; [[SKPaymentQueue defaultQueue] addTransactionObserver:manager]; }); return manager; } - (void)dealloc { [[SKPaymentQueue defaultQueue] removeTransactionObserver:self]; } // 请求可卖的商品 - (void)requestProducts { if (![SKPaymentQueue canMakePayments]) { // 您的手机没有打开程序内付费购买 return; } // 1.请求所有的商品ID NSString *productFilePath = [[NSBundle mainBundle] pathForResource:@"iapdemo.plist" ofType:nil]; NSArray *products = [NSArray arrayWithContentsOfFile:productFilePath]; // 2.获取所有的productid NSArray *productIds = [products valueForKeyPath:@"productId"]; // 3.获取productid的set(集合中) NSSet *set = [NSSet setWithArray:productIds]; // 4.向苹果发送请求,请求可卖商品 _request = [[SKProductsRequest alloc] initWithProductIdentifiers:set]; _request.delegate = self; [_request start]; } /** * 当请求到可卖商品的结果会执行该方法 * * @param response response中存储了可卖商品的结果 */ - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { for (SKProduct *product in response.products) { // 用来保存价格 NSMutableDictionary *priceDic = @{}.mutableCopy; // 货币单位 NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; [numberFormatter setLocale:product.priceLocale]; // 带有货币单位的价格 NSString *formattedPrice = [numberFormatter stringFromNumber:product.price]; [priceDic setObject:formattedPrice forKey:product.productIdentifier]; NSLog(@"价格:%@", product.price); NSLog(@"标题:%@", product.localizedTitle); NSLog(@"秒速:%@", product.localizedDescription); NSLog(@"productid:%@", product.productIdentifier); } // 保存价格列表 [[NSUserDefaults standardUserDefaults] setObject:priceDic forKey:@"priceDic"]