Skip to main content

How To Use In-App Purchase In IOS Objective C

IOS - In-App Purchase

In-App purchase is used to purchase additional content or upgrade features with respect to an application.

Steps Involved

Step 1 − In iTunes connect, ensure that you have a unique App ID and when we create the                                application update with the bundle ID and code signing in Xcode with corresponding                            provisioning profile.

Step 2 −
Create a new application and update application information. You can know more about                       this in apple's Add new apps documentation.

Step 3 − Add a new product for in-app purchase in Manage In-App Purchase of your application's                     page.

Step 4 − Ensure you setup the bank details for your application. This needs to be setup for In-App                     purchase to work. Also, create a test user account using Manage Users option in iTunes                       connect page of your app.

Step 5 − The next steps are related to handling code and creating UI for our In-App purchase.

Step 6 − Create a single view application and enter the bundle identifier is the identifier specified in                   iTunes connect.

Step 7 − Update the ViewController.xib

Step 8 − Create IBOutlets for the three labels and the button naming them as productTitleLabel,                         productDescriptionLabel, productPriceLabel and purchaseButton respectively.

Step 9 − Select your project file, then select targets and then add StoreKit.framework.

Step 10 − Update ViewController.h as follows −

        #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

Step 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 successfully" 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.localisedTitle]];  
                 [productDescriptionLabel setText:[NSString stringWithFormat: @"Product Desc:                                 %@",validProduct.localisedDescription]];
                 [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 have to update kTutorialPointProductID to the productID you have created for your In-App Purchase. You can add more than one product by updating the productIdentifiers's NSSet in fetchAvailableProducts. Similarly, handle the purchase related actions for product IDs you add.

Ensure you had logged out of your account in the settings screen. On clicking the Initiate Purchase, select Use Existing Apple ID. Enter your valid test account username and password. You will be shown the alert in a few seconds.

Once your product is purchased successfully, you will get the alert. You can see relevant code for updating the application features where we show alert.



Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...