sk123
sk123

Reputation: 600

How to properly restore purchases using IAP in Swift

I'm trying to display an alert to the user when purchases are restored. But when i debug and print out the number of restored purchases i get 0 transactions were restored. I don't understand why it would bring back 0. I thought i only needed to call to restoreCompletedTransactions() method. I post a notification to notify me if restoration has completed and i doesn't even reach this point. I'm using paymentQueueRestoreCompletedTransactionsFinished(_ pQueue: SKPaymentQueue) to notify me when restoration is done. How can i properly restore the purchases.

let paymentQueue = SKPaymentQueue.default()

func restorePurchases() {
    if !self.canMakePurchases {
            return
     }
     self.paymentQueue.add(self)
     self.paymentQueue.restoreCompletedTransactions()
}

func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
     print("Restore failed")
}

func paymentQueue(_ pQueue: SKPaymentQueue, updatedTransactions pTransactions: [SKPaymentTransaction]) {
     for scanTransaction in pTransactions {
         switch scanTransaction.transactionState {
          case .purchasing:
             break
          case .purchased:
            NotificationCenter.default.post(name: .AppDelegateUserHasPurchasedProductNotification, object: self)
            pQueue.finishTransaction(scanTransaction)
          default:
            pQueue.finishTransaction(scanTransaction)
        }
    }
}

func paymentQueueRestoreCompletedTransactionsFinished(_ pQueue: SKPaymentQueue) {
     print("Received restored transactions: \(pQueue.transactions.count)")
     for scanTansaction in pQueue.transactions {
        switch scanTansaction.transactionState {
         case .restored:
           NotificationCenter.default.post(name: .AppDelegateUserHasRestoredPurchasesNotification, object: self)
           pQueue.finishTransaction(scanTansaction)
          default:
             break
            }
      }
}

The Logs

Received restored transactions: 0

Upvotes: 1

Views: 1745

Answers (1)

matt
matt

Reputation: 534950

Your implementation of

func paymentQueue(_ pQueue: SKPaymentQueue, updatedTransactions pTransactions: [SKPaymentTransaction]) {

is wrong. You have left out the transaction state for when a purchase is restored! You have case .purchased but you forgot case .restored. Put it in. That is where you are notified and can respond.

Upvotes: 2

Related Questions