Game Development Reference
In-Depth Information
Responding to a Successful Purchase
In order to respond to a successful purchase, we had to add an instance of
SKPaymentTransactionObserver to the default SKPaymentQueue back in Listing 10-2. We are now
ready to look at the code that gets called when the SKPaymentQueue successfully processes a
purchase, as shown in Listing 10-8.
Listing 10-8. ExtrasController.m (paymentQueue: updatedTransactions:)
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
for (SKPaymentTransaction* transaction in transactions){
if (transaction.transactionState == SKPaymentTransactionStatePurchased || transaction.
NSString* productIdentifier = transaction.payment.productIdentifier;
[[gameParams purchases] addObject: productIdentifier];
[gameParams writeToDefaults];
[self setGameParams:gameParams];
[queue finishTransaction:transaction];
}
}
In Listing 10-8, we see the tasks paymentQueue:updatedTransactions: as implemented by
the class ExtrasController . In this task, we iterate through each SKPaymentTransaction
in the array transactions. For each SKPaymentTransaction we check to see if the state is
SKPaymentTransactionStatePurchase or SKPaymentTransactionStateRestore . If it is, we add the
product ID of the transaction to our gamePagam 's purchases property and save it. We also update
the UI by calling setGameParams :. Lastly, we inform the queue that we are done working with the
transaction by calling finishTransaction: .
Technically speaking, if the task paymentQueue:updatedTransactions: is a result of the user making
a new purchase the state of the transaction would be SKPaymentTransactionStatePurchased .
But because the type of products we are using are non-consumable, we need to make sure
the user has a way to restore his purchases if his device is reset or if he made the purchase on
another iOS device. In order to handle this, we make sure we allow the transaction state to be
SKPaymentTransactionStateRestored and treat it the same as a new purchase. In order to allow the
user to restore we provide a restore purchases button that calls the code in Listing 10-9.
Listing 10-9. ExtrasController.m (restorePurchasesClicked:)
- (IBAction)restorePurchasesClicked:(id)sender {
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
In Listing 10-9, we see the task trestorePurchasesClicked that gets called when the user clicks the
restore purchases button. In this task, we simply call restoreCompletedTransactions on the default
SKPaymentQueue . This causes StoreKit to contact the iTunes Store and re-download all product IDs
 
Search WWH ::




Custom Search