如何在Swift中使用IAP正确恢复购买

时间:2019-04-10 10:21:46

标签: ios swift in-app-purchase

我正在尝试在恢复购买时向用户显示警报。但是,当我调试并打印出恢复的购买数量时,我得到了0笔交易。我不明白为什么它将返回0。我以为我只需要调用restoreCompletedTransactions()方法。我发布了通知以通知我恢复是否已完成,甚至还没有达到这一点。我在用着 paymentQueueRestoreCompletedTransactionsFinished(_ pQueue: SKPaymentQueue)通知我还原完成。我如何正确恢复购买的商品。

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
            }
      }
}

日志

Received restored transactions: 0

1 个答案:

答案 0 :(得分:2)

您的实现

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

是错误的。您已省略恢复购买时的交易状态!您有case .purchased,但您忘记了case .restored。放入。这是通知您并可以做出回应的地方。