2017年6月9日 | Leave a comment 问题: 解决: xcode target 属性启用 In-app purchase 在itunesConnect 后台app 功能下添加 内购产品,记住填写的商品id; 添加测试用户(可选) 在代码中使用 商品id获取SKProduct Swift req = SKProductsRequest(productIdentifiers: Set([**商品id**])) req.delegate = self req.start() 123 req = SKProductsRequest(productIdentifiers: Set([**商品id**])) req.delegate = self req.start() 获取到SKProduct 后 会回调 func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { let pay = SKMutablePayment(product: response.products[0])//todo pay.quantity = 1 SKPaymentQueue.default().add(pay) } 12345 func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { let pay = SKMutablePayment(product: response.products[0])//todo pay.quantity = 1 SKPaymentQueue.default().add(pay) } 购买有结果后会回调 /* 需要组成 transaction observer 才会调用下边的函数 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { .... SKPaymentQueue.default().add(self) .... } */ func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for t in transactions { if t.transactionState == .purchased { //unlock function queue.finishTransaction(t) } else if t.transactionState == .restored { //unlock function queue.restoreCompletedTransactions() } } } 12345678910111213141516171819 /*需要组成 transaction observer 才会调用下边的函数 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {.... SKPaymentQueue.default().add(self).... }*/ func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for t in transactions { if t.transactionState == .purchased {//unlock function queue.finishTransaction(t) } else if t.transactionState == .restored {//unlock function queue.restoreCompletedTransactions() } } } 退出iphone 上app store 的登录账号,进入app 购买流程,输入账号时使用步骤2中添加的测试账号测试购买(切换成正式账号就能把测试账号踢掉) 必须有恢复购买功能,恢复购买时需要调用 Swift SKPaymentQueue.default().restoreCompletedTransactions() 1 SKPaymentQueue.default().restoreCompletedTransactions() 参考: https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Chapters/ShowUI.html#//apple_ref/doc/uid/TP40008267-CH3-SW6 https://developer.apple.com/library/content/technotes/tn2259/_index.html#//apple_ref/doc/uid/DTS40009578