Search code examples
iosswiftstorekit

Swift: How to notify when purchase is complete


I have a SKPaymentTransactionObserver checking when purchase is complete

extension IAPService: SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    for transaction in transactions {
        print(transaction.transactionState.status(), transaction.payment.productIdentifier)
        if transaction.transactionState.status() == "purchased" {
            // Pro Purchased
        }
        switch transaction.transactionState {
        case .purchasing: break
        default: queue.finishTransaction(transaction)
        }
    }
}
}

How can I hide an object on the ViewController, purchased from when purchase is complete


Solution

  • You can create a closure in your IAPService class:

    var productDidPurchased: (() -> Void)?
    

    Then in your extension you can use it in this way:

    switch transaction.transactionState {
        case .purchasing: 
            break
        case .purchased:
            productDidPurchased?()
        default:
            queue.finishTransaction(transaction)
    }
    

    Then in your ViewController to retrieve it:

    IAPService.shared.productDidPurchased = { 
        [weak self] in 
        //you will receive a callback when the product is purchased and can hide your view here 
    }