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

Master Map & Filter, Javascript’s Most Powerful Array Functions

Master Map & Filter, Javascript’s Most Powerful Array Functions Learn how Array.map and Array.filter work by writing them yourself This article is for those who have written a  for  loop before, but don’t quite understand how  Array.map  or  Array.filter  work. You should also be able to write a basic function. By the end of this, you’ll have a complete understanding of both functions, because you’ll have seen how they’re written. Array.map Array.map  is meant to transform one array into another by performing some operation on each of its values. The original array is left untouched and the function returns a new, transformed array. For example, say we have an array of numbers and we want to  multiply each number by three . We also don’t want to change the original array. To do this without  Array.map , we can use a standard for-loop. for-loop var originalArr = [1, 2, 3, 4, 5]; var newArr = []; for(var i = 0; i < originalArr.length; i+...

Integrate the FaceID or TouchID Authentication in iOS Apps - Swift

FaceID or TouchID Authentication Dear Folks, today I am going to explain the proper way to integrate the Face ID or Touch ID in iOS App. Face ID and Touch ID are secure, familiar authentication methods that people trust. Follow below steps: Step 1: Add NSFaceIDUsageDescription Key in info.plist file <key>NSFaceIDUsageDescription</key> <string>This app requires Face ID permission to authenticate using Face recognition.</string> Step 2: Create a swift file with any name but it would be better to related to its functionality, Like BioMetrixFile.swift Step 3: In BioMetrixFile write below codes and follow instructions. But before proceeding further import LocalAuthentication class in BioMetrixFile. Now, create typealias for success or failure blocks to well manage Authentication Success or Failure. public typealias AuthenticationSuccess = (() -> ()) public typealias AuthenticationFailure = ((AuthenticationError) -> ()) Now written all s...

React Native: How To Open App Settings Page

  React Native: How To Open App Settings Page React Native has a Linking module to manage the interaction with other applications in the device. In this article, I will explain how you can open “Application Setting Page” of the device using. Sample Case Before I explain how to do this, I’ll talk about an example case where we might need this: You need to get location permission within the application from a user using an iOS operating system and you asked for permission. But user did not agree to grant this permission the first time. In this case, you cannot ask your user for location permission the second time. In this case, the only thing to do is to direct the user to the settings page of our application and make it manually allow it. Now that we have explained our example situation, we can move on to how we can redirect our user to the “settings page of our application”. Open App Settings Page iOS If our user is using an iOS operating system, we can handle the whole process wit...