Easiest Way To Implement Restore Purchase Function To Your App

photo from: mobil-ganz-einfach.de
A Restore Purchase function in any iOS Project/App is necessary. First is because App Store or Apple will not accept your project if they detect In App Purchase on your app. So let's get started, this will be a quick tutorial, since it is quite easy to implement.

You do not have to install third party libraries like MKStoreKit for Restoring Purchases.

First step, import StoreKit.

@import StoreKit;

Above is what we call 'Semantic Import'. Again, one of its advantages is that you'll never have to import the library or framework in your project settings.

Next, in your selector or method, use this code:
// RESTORE PURCHASE
-(void)restorePreviousPurchase{
    // You can add HUDs here to tell the user 'Please Wait...'
   
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

Finally, add these delegate methods:

- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
    NSLog(@"received restored transactions: %i", queue.transactions.count);
    if( queue.transactions.count == 0 ) {
        // no restored purchases

    } else {
        // user has purchases before
        // SUCCESS RESTORE PURCHASE, DO YOUR NEXT TASKS HERE
        // example: Show Alert, Store defaults, etc...
    }
    
    // DIMISS THE HUD
}

- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error {
    NSLog(@"%@",error);
    
    // DISMISS THE HUD
    // Do whatever you want here
}

- (void)failedTransaction:(SKPaymentTransaction *)transaction
{
    // DISMISS THE HUD
}

So there you go. I put important comments to the codes above to make your life easier. If you have any questions, just post it in the comment section or contact me. Cheers! Subscribe!

Post a Comment