应用内购买 Swift

In-App Purchase Swift

我正在使用 IAPHelper 实现应用内购买,当我按下购买按钮后转到另一个视图控制器时出现错误。例如,当我按下购买按钮然后转到另一个视图控制器时,在完成购买工作后出现错误。

class selectQuestion_ViewController:  UITableViewController, UITableViewDelegate, UITableViewDataSource{

let helper = IAPHelper(productIdentifiers: NSSet(object: "sppid") as Set<NSObject>)
 func purchase(sender: AnyObject)
    {
        startLoading("Purchasing ..")
        self.helper.requestProductsWithCompletionHandler({ (success, products) -> Void in

            if success {
                self.endLoading()
                println("wohooooo")
                var sdad =  self.helper.productsDict["sppid"]
                self.helper.buyProduct(sdad!)

            } else {
                self.endLoading()
                let alert = UIAlertController(title: "Error", message: "Cannot retrieve products list right now.", preferredStyle: .Alert)
                alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
                self.presentViewController(alert, animated: true, completion: nil)
            }


        })
    }

我建议您不要使用此类模块。查看本教程并实现其中描述的代码和方法对您和您对 IAP 的理解会更好:https://www.youtube.com/watch?v=h1gQklbrgjc

一旦您实现了该代码,如果某些地方不起作用(您可能在某处忘记了一行),请返回 SO,我们将很乐意帮助您。作为快速帮助,这里有一个答案可以帮助您解决大多数错误,一旦您使用 IAP 助手以外的其他东西实现 IAP 代码:

事实上,你可以观看视频并复制粘贴我的问题的代码。我的 IAP 代码有效 ;) 将节省您的时间。但是请观看视频以了解如何实施 IAP!

希望这个回答对您有所帮助 ;)

这是完整的 IAP 代码:

import UIKit
import StoreKit


class GameViewController: UIViewController, ADBannerViewDelegate, SKProductsRequestDelegate, SKPaymentTransactionObserver, GKGameCenterControllerDelegate,GADBannerViewDelegate{


    @IBOutlet var outRemoveAds: UIButton!
    @IBOutlet var outRestorePurchases: UIButton!


    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        if NSUserDefaults.standardUserDefaults().objectForKey("val") != nil {
            print("Has a value.")
            banner.removeFromSuperview()
            bannerGoogle.removeFromSuperview()
            outRemoveAds.removeFromSuperview()
            outRestorePurchases.removeFromSuperview()
            removeInterFrom = 1
        }
        else {
            print("No Value.")
        }

        if(SKPaymentQueue.canMakePayments()){
            print("IAP is enabled, loading...")
            let productID:NSSet = NSSet(objects:"IAP id")
            let request: SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>)
            request.delegate = self
            request.start()
        }
        else{
            print("Please enable IAPS")

        }

    }


    //IAP Ads

    @IBAction func removeAds(sender: UIButton) {
        for product in list{
            let prodID = product.productIdentifier
            if (prodID == "IAP id"){
                p = product
                buyProduct()
                break
            }
        }
    }
    @IBAction func restorePurchases(sender: UIButton) {
        SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
    }


    //IAP Functions

    var list = [SKProduct]()
    var p = SKProduct()

    func removeAds(){
        banner.removeFromSuperview()
        bannerGoogle.removeFromSuperview()
        outRemoveAds.removeFromSuperview()
        outRestorePurchases.removeFromSuperview()
        let theValue = 10
        NSUserDefaults.standardUserDefaults().setObject(theValue, forKey: "val")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

    func buyProduct(){
        print("Buy: "+p.productIdentifier)
        let pay = SKPayment (product: p)
        SKPaymentQueue.defaultQueue().addPayment(pay as SKPayment)
    }

    func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
        print("Product Request")
        let myProduct = response.products

        for product in myProduct{
            print("Product Added")
            print(product.productIdentifier)
            print(product.localizedTitle)
            print(product.localizedDescription)
            print(product.price)

            list.append(product as SKProduct)
        }
    }

    func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        print("Add Payment")

        for transaction:AnyObject in transactions{
            let trans = transaction as! SKPaymentTransaction
            print(trans.error)
            switch trans.transactionState{
            case .Purchased:
                print("IAP unlocked")
                print(p.productIdentifier)

                let prodID = p.productIdentifier as String
                switch prodID{
                case "IAP id":
                    print("Remove Ads")
                    removeAds()
                default:
                    print("IAP not setup")
                }
                queue.finishTransaction(trans)
                break
            case .Failed:
                print ("Buy error")
                queue.finishTransaction(trans)
                break
            default:
                print("default: Error")
                break
            }
        }
    }

    func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {
        print("Purchases Restored")

        _ = []
        for transaction in queue.transactions {
            let t: SKPaymentTransaction = transaction as SKPaymentTransaction

            let prodID = t.payment.productIdentifier as String
            switch prodID{
            case "IAP id":
                print("Remove Ads")
                removeAds()
            default:
                print("IAP not setup")
            }


        }
    }
    func finishTransaction(trans:SKPaymentTransaction){
        print("Finshed Transaction")
    }

    func paymentQueue(queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
        print("Remove Transaction")
    }
}

放:

SKPaymentQueue.defaultQueue().addTransactionObserver(self) 

在 viewDidLoad 或 viewDidAppear 中