在iTunesConnect中创建IAP之后:
在您要购买的视图控制器中
import StoreKit
并添加相关代表
class ViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {
从iTunesConnect声明具有产品ID的变量
var product_id: NSString? override func viewDidLoad() { product_id = "YOUR_PRODUCT_ID" super.viewDidLoad() SKPaymentQueue.defaultQueue().addTransactionObserver(self) //检查是否购买了产品 if (NSUserDefaults.standardUserDefaults().boolForKey("purchased")){ // 隐藏广告 adView.hidden= true } else { print("应该显示广告...") } }
将按钮连接至功能以购买IAP
@IBAction func unlockAction(sender: AnyObject) { print("即将获取产品...") // 可以付款 if (SKPaymentQueue.canMakePayments()) { let productID:NSSet = NSSet(object: self.product_id!); let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<NSString>); productsRequest.delegate= self; productsRequest.start(); println("Fetching Products"); }else{ print("Can't make purchases"); } }
这是一些帮助方法
func buyProduct(product: SKProduct){ println("Sending the Payment Request to Apple"); let payment = SKPayment(product: product) SKPaymentQueue.defaultQueue().addPayment(payment); }
必须声明的委托方法
func productsRequest (request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) { let count : Int = response.products.count if (count>0) { var validProduct: SKProduct = response.products[0] as SKProduct if (validProduct.productIdentifier == self.product_id) { print(validProduct.localizedTitle) print(validProduct.localizedDescription) print(validProduct.price) buyProduct(validProduct); } else { print(validProduct.productIdentifier) } } else { print("nothing") } } func request(request: SKRequest!, didFailWithError error: NSError!) { print("Error Fetching product information"); } func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { print("Received Payment Transaction Response from Apple"); for transaction:AnyObject in transactions { if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{ switchtrans.transactionState{ case .Purchased: print("Product Purchased"); SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction) // 处理购买 NSUserDefaults.standardUserDefaults().setBool(true , forKey: "purchased") adView.hidden= true break; case .Failed: print("Purchased Failed"); SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction) break; case .Restored: print("Already Purchased"); SKPaymentQueue.defaultQueue().restoreCompletedTransactions() // 处理购买 NSUserDefaults.standardUserDefaults().setBool(true , forKey: "purchased") adView.hidden= true break; default: break; } } } }
然后使用代码还原应用中的非消耗品购买
if (SKPaymentQueue.canMakePayments()) { SKPaymentQueue.defaultQueue().restoreCompletedTransactions() }