fredericdnd
fredericdnd

Reputation: 1008

Restore Purchases function - Swift

In my app, the user can make two different purchases.

Here's my paymentQueue function :

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 {
            switch trans.transactionState {

            case .Purchased, . Restored:
                print("Product Purchased / Restored")
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)

                // TO DO
                if selectedProduct == "product1" {
                    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "product1Purchased")
                } else if selectedProduct == "product2" {
                    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "product2Purchased")
                }
            case .Failed:
                print("Purchased Failed")
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
                break
            default:
                break
            }
        }
    }
}

I created a variable named selectedProduct to detect which product the user select. If he click on the button to buy the first product, the variable selectedProduct hold the value "product1".

The problem is when the user click the Restore Purchases button, the app check if the selected product is "product1" or "product2", but selectedProduct has no value if the user click on the Restore Purchases button, so nothing happen.

How can I do please?

Upvotes: 1

Views: 410

Answers (1)

rmaddy
rmaddy

Reputation: 318774

Do not use a variable such as selectedProduct to determine which product was purchased or restored. Look inside the SKPaymentTransaction for the needed information.

        case .Purchased, . Restored:
            print("Product Purchased / Restored")
            SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)

            if trans.payment.productIdentifier == "product1" {
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "product1Purchased")
            } else if trans.payment.productIdentifier == "product2" {
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "product2Purchased")
            }

Adjust as needed for your actual product ids.

Upvotes: 1

Related Questions