Game Development Reference
In-Depth Information
The dialog on the upper left side of the figure will always be shown, as well as the one on the lower
right. The other two dialogs will be shown between the first and last dialog if the user has to log in
with his Apple ID. It is important to remember that, as a developer, we have no control over exactly
which dialogs will be displayed or how long the user will take to complete the process. It is important
not to expect the user to complete this process while the action of the game is in process.
Now let's look at a specific example, where we implement the purchase of a nonconsumable
in-app purchase for our game Belt Commander. We are going to implement the view from Figure
10-1
,
where the user can select which actors are involved in the game and purchase new actors to be
made available.
In-App Purchase Implementation
As we discussed, the process of making a purchase is really just two calls to the iTunes Store. We
will see in this section that it really only involves a handful of classes. In our example, we will be
handling most of the details of working with StoreKit and handling the UI in a single class called
ExtrasController
, whose header is shown in Listing 10-1.
Listing 10-1. ExtrasController.h
@interface ExtrasController : UIViewController<SKPaymentTransactionObserver, SKProductsRequestDelegate>{
GameParameters* gameParams;
NSMutableDictionary* idsToProducts;
}
@property (strong, nonatomic) IBOutlet UIButton *asteroidButton;
@property (strong, nonatomic) IBOutlet UIButton *saucerButton;
@property (strong, nonatomic) IBOutlet UIButton *powerupButton;
-(void)setGameParams:(GameParameters*)params;
@end
In Listing 10-1, we see the header for the class
ExtrasController
. The class
ExtrasController
plays
two roles: it manages the purchasing process and it updates the three buttons accordingly.
The object
gameParams
is responsible for storing which actors are enabled in the game and which
purchases have been made. The object
idsToProducts
is used to map our ids for purchases to
SKProduct
objects that Apple tells us are valid; we will see how we use these objects shortly.
In order to interact with StoreKit,
ExtrasController
conforms to the protocols
SKPaymentTransactionObserver
and
SKProductsRequestDelegate
. These protocols provide
everything you need for your application to respond to interactions with the store. We will see how
ExtrasController
implements the tasks from these two protocols as we work through the code.
The first step when working StoreKit is to set up an object that responds to changes in the state of
purchases. We create an object that responds to changes in purchases by adding an observer to the
default
SKPaymentQueue
, as shown in Listing 10-2.