使用单一产品在Swift中进行应用内购买

时间:2014-10-07 12:18:31

标签: ios swift in-app-purchase storekit

是否有一种简单的方法可以在swift中为单个产品实施应用内购买?

我想要一个触发应用内购买的按钮,如[ad-removal]或[unlock-premium-content]

我无法理解它的完整逻辑。

我正在尝试从[Techotopia] http://www.techotopia.com/index.php/An_iOS_7_In-App_Purchase_Tutorial

关注并翻译本教程

但这是我第一次使用StoreKit Framework,也使用Swift。

我只是想了解使用Swift StoreKit Framework进行应用内购买交易的逻辑。

谢谢!

3 个答案:

答案 0 :(得分:50)

步骤0:在iTunes Connect帐户中,创建应用内购买。

对于单次购买,请使用此方法:

  1. 导入
  2. import StoreKit
    
    1. 符合StoreKit Delegate
    2. class YOURViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {
      
      1. 使用用户默认值跟踪交易
      2. let defaults = NSUserDefaults.standardUserDefaults()
        
        1. 产品ID。这个将与iTunes iTunes in app purchase
        2. 中的相同
          var product_id: NSString?
          
          override func viewDidLoad() {        
              product_id = "YOUR_PRODUCT_ID"
              super.viewDidLoad()
              SKPaymentQueue.defaultQueue().addTransactionObserver(self)
          
              //Check if product is purchased
          
              if (defaults.boolForKey("purchased")){  
                 // Hide a view or show content depends on your requirement
                 overlayView.hidden = true     
              } else if (!defaults.boolForKey("stonerPurchased")) {
                  print("false")            
              }
          }
          
          1. 解锁内容。这是按钮操作,将初始化购买
          2. @IBAction func unlockAction(sender: AnyObject) {
            
               print("About to fetch the products")
            
               // We check that we are allow to make the purchase.
               if (SKPaymentQueue.canMakePayments()) {
                    var productID:NSSet = NSSet(object: self.product_id!);
                    var productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID);
                    productsRequest.delegate = self;
                    productsRequest.start();
                    println("Fetching Products");
                } else {
                    print("can't make purchases");
                }    
            }
            
            1. 帮助方法
            2. func buyProduct(product: SKProduct) {
                  println("Sending the Payment Request to Apple");
                  var payment = SKPayment(product: product)
                  SKPaymentQueue.defaultQueue().addPayment(payment);
              }
              
              1. IAP的代表方法
              2. func productsRequest (request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
                
                    var count : Int = response.products.count
                    if (count>0) {
                        var validProducts = response.products
                        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: [AnyObject]!)    {
                    print("Received Payment Transaction Response from Apple");
                
                    for transaction:AnyObject in transactions {
                        if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{
                            switch trans.transactionState {
                            case .Purchased:
                                print("Product Purchased");
                                SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
                                defaults.setBool(true , forKey: "purchased")
                                overlayView.hidden = true
                                break;
                            case .Failed:
                                print("Purchased Failed");
                                SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
                                break;
                            case .Restored:
                                print("Already Purchased");
                                SKPaymentQueue.defaultQueue().restoreCompletedTransactions()    
                            default:
                                break;
                            }
                        }
                    }        
                }
                

                Swift> 3.0

                import StoreKit
                class YOURVIEWController:UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {
                
                let product_id: NSString = "com.some.inappid" // <!-- Change it to your inapp id
                

                viewDidLoad添加

                override func viewDidLoad() {
                    super.viewDidLoad()
                    SKPaymentQueue.default().add(self)
                

                在您的购买按钮操作

                @IBAction func buyNowAction(_ sender: UIButton) {
                
                
                    if (SKPaymentQueue.canMakePayments()) {
                        let productID:NSSet = NSSet(array: [self.product_id as NSString]);
                        let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>);
                        productsRequest.delegate = self;
                        productsRequest.start();
                        print("Fetching Products");
                    } else {
                        print("can't make purchases");
                    }
                }
                

                在“还原”按钮操作

                // MARK: - Restore In App Purchase
                    @IBAction func restoreAction(_ sender: UIButton) {
                
                    if (SKPaymentQueue.canMakePayments()) {
                        SKPaymentQueue.default().add(self)
                        SKPaymentQueue.default().restoreCompletedTransactions()
                    } else {
                        // show error
                    }
                
                }
                

                添加代表:

                // SKProductRequest Delegate
                
                func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
                
                    print(response.products)
                    let count : Int = response.products.count
                    if (count>0) {
                
                        let validProduct: SKProduct = response.products[0] as SKProduct
                        if (validProduct.productIdentifier == self.product_id as String) {
                            print(validProduct.localizedTitle)
                            print(validProduct.localizedDescription)
                            print(validProduct.price)
                            self.buyProduct(product: validProduct)
                        } else {
                            print(validProduct.productIdentifier)
                        }
                    } else {
                        print("nothing")
                    }
                }
                
                func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
                    for transaction:AnyObject in transactions {
                        if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{
                
                            self.dismissPurchaseBtn.isEnabled = true
                            self.restorePurchaseBtn.isEnabled = true
                            self.buyNowBtn.isEnabled = true
                
                            switch trans.transactionState {
                            case .purchased:
                                print("Product Purchased")
                                //Do unlocking etc stuff here in case of new purchase
                                SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
                
                                break;
                            case .failed:
                                print("Purchased Failed");
                                SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
                                break;
                            case .restored:
                                print("Already Purchased")
                                //Do unlocking etc stuff here in case of restor
                
                                SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
                            default:
                                break;
                            }
                        }
                    }
                }
                
                
                //If an error occurs, the code will go to this function
                    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
                        // Show some alert
                    }
                

答案 1 :(得分:4)

在应用程序中购买委托方法:

func buyInApp()
{
    if (SKPaymentQueue.canMakePayments())
    {
        let productID:NSSet = NSSet(object: "com.valueedge.plane_post");
        let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>);
        productsRequest.delegate = self;
        productsRequest.start();
    }
    else
    {
        MBProgressHUD.hideHUDForView(self.view, animated: true)
    }
}

func productsRequest (request: SKProductsRequest, didReceiveResponse response: SKProductsResponse)
{
    let count : Int = response.products.count
    if (count>0)
    {
        let validProduct: SKProduct = response.products[0] as SKProduct

        if (validProduct.productIdentifier == "com.valueedge.plane_post")
        {
            buyProduct(validProduct);
        }
        else
        {
            MBProgressHUD.hideHUDForView(self.view, animated: true)
        }
    }
    else
    {
        MBProgressHUD.hideHUDForView(self.view, animated: true)
    }
}

func buyProduct(product: SKProduct)
{
    let payment = SKPayment(product: product)
    SKPaymentQueue.defaultQueue().addPayment(payment)
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
}

func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction])
{
    for transaction:AnyObject in transactions
    {
        if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction
        {
            switch trans.transactionState
            {
            case .Purchased:
                self.PaymentSuccess("Apple", details: "Apple(In-App)")
                print("In App Payment Success")
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
                MBProgressHUD.hideHUDForView(self.view, animated: true)
                break
            case .Failed:
                MBProgressHUD.hideHUDForView(self.view, animated: true)
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)

                let alert = UIAlertController(title: "Planes Only", message: "Payment failed", preferredStyle: .Alert)
                alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action:UIAlertAction!) in
                }))
                self.presentViewController(alert, animated: true, completion: nil)

                break
            case .Restored :
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
                MBProgressHUD.hideHUDForView(self.view, animated: true)
                break
            default:
                MBProgressHUD.hideHUDForView(self.view, animated: true)
                break
            }
        }
    }
}

func restore()
{
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
    MBProgressHUD.showHUDAddedTo(self.view, animated: true)
}

func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue)
{
    for transact:SKPaymentTransaction in queue.transactions
    {
        if transact.transactionState == SKPaymentTransactionState.Restored
        {
            //let t: SKPaymentTransaction = transact as SKPaymentTransaction
            //let prodID = t.payment.productIdentifier as String
            //restore prodID
            SKPaymentQueue .defaultQueue().finishTransaction(transact)
            MBProgressHUD.hideHUDForView(self.view, animated: true)
        }
    }
}

func paymentQueue(queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: NSError)
{
    for transaction:SKPaymentTransaction  in queue.transactions
    {
        if transaction.transactionState == SKPaymentTransactionState.Restored
        {
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
            MBProgressHUD.hideHUDForView(self.view, animated: true)
            break
        }
    }
    MBProgressHUD.hideHUDForView(self.view, animated: true)
}

func request(request: SKRequest, didFailWithError error: NSError)
{
    MBProgressHUD.hideHUDForView(self.view, animated: true)
}

在应用按钮点击事件:

@IBAction func In_App_Payment_Clicked(sender: AnyObject)
{
    MBProgressHUD.showHUDAddedTo(self.view, animated: true)
    self.buyInApp()
}

答案 2 :(得分:2)

对于应用购买应用中的开发,即使只是简单的方式,您需要解决与编码无关的下一个子任务:

    • 注册为开发人员并在https://developer.apple.com/account/
    • 下创建应用ID
    • 选择证书,ID和&amp;轮廓。
    • 选择标识符&gt;应用ID,然后点击 + 以创建新的应用ID。
    • 确保为您的应用ID启用了应用内购买。
    • 填写协议和银行信息。登录https://itunesconnect.apple.com/
    • 重要步骤 - 仔细检查“协议”,“税务”和“银行业务”部分。所有这些都应该填写。在其他情况下,应用程序购买将无法正常工作您将从服务器收到失败的响应。
    • 在iTunes Connect中创建应用。只需点击https://itunesconnect.apple.com/下的我的应用按钮
    • 创建应用内购买产品。在您的情况下消耗品或非消耗品。对于管理耗材或非耗材代码将类似。
  1. 创建沙盒用户或用户。在iTunes Connect中创建应用。为此,只需转到https://itunesconnect.apple.com/点击以选择用户和角色按钮,然后点击沙箱测试人员标签。创建用户 - &gt;并转到测试电子邮件并通过电子邮件确认用户!
  2. 要开始开发并检查itunesconnect与您的应用之间的连接,您可以使用模拟器。但是当您尝试购买产品时,您需要使用真实设备。
  3. 对于在应用内购买的ios应用程序必须具有购买按钮 “恢复购买”按钮也应该开发。 (例如在Android应用中,它不是强制性的,Android应用程序以不同的方式检查它)。如果用户删除他的应用并再次安装它,他想恢复已购买的商品。为此,应该开发 “恢复购买”