Easy Tutorial
❮ Ios Gamekit Att Ios Ui Alerts ❯

In-App Purchases for iOS

Introduction

In-App Purchases allow an app to buy additional content or upgrade features.

Steps to Implement

  1. Ensure you have a unique App ID in iTunes Connect. When creating a bundle ID for app updates, the code will be signed with the corresponding provisioning profile in Xcode.

  2. Create a new app and update the app information. You can find more details in Apple's documentation on adding new apps.

  3. In the Manage In-App Purchases section of the app page, add a new product for in-app purchases.

  4. Ensure that the banking details are set up for in-app purchases. Additionally, use the Manage Users option in iTunes to create a test user account linked to your app's page.

  5. The next step involves writing code and creating the UI related to in-app purchases.

  6. Create a single view application and enter the bundle identifier in the specified identifier field in iTunes.

  7. Update ViewController.xib as shown.

  8. Create IBOutlets for three labels and name the buttons productTitleLabel, productDescriptionLabel, productPriceLabel, and purchaseButton.

  9. Select the project file, then select the target, and add the StoreKit.framework.

  10. Update ViewController.h as shown:

    #import <UIKit/UIKit.h>
    #import <StoreKit/StoreKit.h>
    
    @interface ViewController : UIViewController<
    SKProductsRequestDelegate,SKPaymentTransactionObserver>
    {
        SKProductsRequest *productsRequest;
        NSArray *validProducts;
        UIActivityIndicatorView *activityIndicatorView;
        IBOutlet UILabel *productTitleLabel;
        IBOutlet UILabel *productDescriptionLabel;
        IBOutlet UILabel *productPriceLabel;
        IBOutlet UIButton *purchaseButton;
    }
    - (void)fetchAvailableProducts;
    - (BOOL)canMakePurchases;
    - (void)purchaseMyProduct:(SKProduct*)product;
    - (IBAction)purchase:(id)sender;
    
    @end
    
  11. Update ViewController.m as shown:

    #import "ViewController.h"
    #define kTutorialPointProductID 
    @"com.tutorialPoints.testApp.testProduct"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Adding activity indicator
        activityIndicatorView = [[UIActivityIndicatorView alloc]
        initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        activityIndicatorView.center = self.view.center;
        [activityIndicatorView hidesWhenStopped];
        [self.view addSubview:activityIndicatorView];
        [activityIndicatorView startAnimating];
        //Hide purchase button initially
        purchaseButton.hidden = YES;
        [self fetchAvailableProducts];    
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
    
// Dispose of any resources that can be recreated.
}

-(void)fetchAvailableProducts{
    NSSet *productIdentifiers = [NSSet 
    setWithObjects:kTutorialPointProductID,nil];
    productsRequest = [[SKProductsRequest alloc] 
    initWithProductIdentifiers:productIdentifiers];
    productsRequest.delegate = self;
    [productsRequest start];
}

- (BOOL)canMakePurchases
{
    return [SKPaymentQueue canMakePayments];
}
- (void)purchaseMyProduct:(SKProduct*)product{
    if ([self canMakePurchases]) {
        SKPayment *payment = [SKPayment paymentWithProduct:product];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
    else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
        @"Purchases are disabled in your device" message:nil delegate:
        self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alertView show];
    }
}
-(IBAction)purchase:(id)sender{
    [self purchaseMyProduct:[validProducts objectAtIndex:0]];
    purchaseButton.enabled = NO; 
}

#pragma mark StoreKit Delegate

-(void)paymentQueue:(SKPaymentQueue *)queue 
 updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                    NSLog(@"Purchasing");
                break;                
            case SKPaymentTransactionStatePurchased:
               if ([transaction.payment.productIdentifier 
                  isEqualToString:kTutorialPointProductID]) {
                   NSLog(@"Purchased ");
                   UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                   @"Purchase is completed succesfully" message:nil delegate:
                   self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                   [alertView show];
                }               
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
switch (transaction.transactionState) {
    case SKPaymentTransactionStatePurchased:
        NSLog(@"Purchased");
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        break;
    case SKPaymentTransactionStateRestored:
        NSLog(@"Restored");
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        break;
    case SKPaymentTransactionStateFailed:
        NSLog(@"Purchase failed");
        break;
    default:
        break;
}
}
}

- (void)productsRequest:(SKProductsRequest *)request
     didReceiveResponse:(SKProductsResponse *)response {
    SKProduct *validProduct = nil;
    int count = [response.products count];
    if (count > 0) {
        validProducts = response.products;
        validProduct = [response.products objectAtIndex:0];
        if ([validProduct.productIdentifier isEqualToString:kTutorialPointProductID]) {
            [productTitleLabel setText:[NSString stringWithFormat:@"Product Title: %@", validProduct.localizedTitle]];
            [productDescriptionLabel setText:[NSString stringWithFormat:@"Product Desc: %@", validProduct.localizedDescription]];
            [productPriceLabel setText:[NSString stringWithFormat:@"Product Price: %@", validProduct.price]];
        }
    } else {
        UIAlertView *tmp = [[UIAlertView alloc] initWithTitle:@"Not Available"
                                                       message:@"No products to purchase"
                                                      delegate:self
                                             cancelButtonTitle:nil
                                             otherButtonTitles:@"Ok", nil];
        [tmp show];
    }
    [activityIndicatorView stopAnimating];
    purchaseButton.hidden = NO;
}

@end

Note: You need to modify the kTutorialPointProductID for your In-App Purchase creation. By modifying the NSSet of product identifiers in fetchAvailableProducts, you can add multiple products.

Output

Run the application, and the output will be as follows:

Ensure that you are logged in. Click Purchase and select an existing Apple ID. Enter the username and password of a valid test account. After a few seconds, the following message will be displayed:

Once the product is successfully purchased, you will receive the following message. You can update the code related to app functionality where this message is displayed.

❮ Ios Gamekit Att Ios Ui Alerts ❯