Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

iOS In-App Purchase

IOS In-App Purchase


Introduction

In-app purchase is used by an application to buy additional content or upgrade features.

Example Steps

1. In iTunes Connect, please make sure you have a unique App ID (unique App ID); when creating the bundle ID (bundle ID) for the application update, the code will be signed with the corresponding provisioning profile in Xcode

2. Create a new application and update the application information. You can learn more in Apple's Adding a New Application documentation

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

4. Make sure the application's bank details are set. It needs to be set for In-App purchase. Also, in iTunes Connect use the Manage Users option to create a test user account for your application.

5. The next step is to work with the code and create the relevant UI for our in-app purchase.

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

7. Update ViewController.xib as follows

InAppPurchase_OutputInterface

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

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

10. Update ViewController.h as follows



#import 

#import 



@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 follows



#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];

                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 you created for In-App Pur (in-app purchase). By modifying the NSSet of product identifiers in fetchAvailableProducts, you can add multiple products.

Output

Run the application; the output is as follows

InAppPurchase_Output1

Make sure you are logged in. Click Purchase and select an existing Apple ID. Enter a valid test account's username and password. After a few seconds, the following message is displayed

InAppPurchase_Output2

Once the product is successfully purchased, the following message will be obtained. Where this message is displayed, you can update the code related to the application's functionality

InAppPurchase_Output3