user339946 user339946 - 4 months ago 9
iOS Question

In-App purchasing: Listen for the "Cancel' button?

I'm trying to figure out how I can listen to the "Cancel" button that appears in the "confirmation" alert shown when a user tries to purchase something. You know, the official one done by Apple, looks something like: "Confirm Your In App Purchase. Do you want to buy one $product for $price? [Cancel] [Buy]"

If I understand my code correctly, the alert initiated by something like this:

SKPayment *payment = [SKPayment paymentWithProductIdentifier:productIdentifier];
[[SKPaymentQueue defaultQueue] addPayment:payment];


So basically I'd like to do something if they hit Cancel. Thanks

Answer

implement the paymentQueue:updatedTransactions: method from the SKPaymentTransactionObserver Protocol. There you can check the transactionState and the error of each transaction object.

I used something like that:

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                if (transaction.error.code == SKErrorPaymentCancelled) {
                    /// user has cancelled
                    [self finishTransaction:transaction wasSuccessful:NO];
                }
                else if (transaction.error.code == SKErrorPaymentNotAllowed) {
                    // payment not allowed
                    [self finishTransaction:transaction wasSuccessful:NO];
                }
                else {
                    // real error
                    [self finishTransaction:transaction wasSuccessful:NO];
                    // show error
                }
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
                break;
            default:
                break;
        }
    }
}
Comments