How to set up In-App Purchase in iOS App

Views:
 
Category: Entertainment
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

slide 1:

How to set up In-App Purchase in iOS App This framework connects to the App Store on your app’s behalf to securely process payments                               from users prompting them to authorize payment.    In-app purchasing is implemented using the StoreKit Framework introduced with iOS 3.0 your                           application receives information from StoreKit alerting you to when a user makes a purchase                             and StoreKit then delivers that purchased item to the user. Without StoreKit you would not be                                 able to showcase products in an in-app store.  The StoreKit implementation can be divided into three main sections:  1 Set up of products done in iTunes Connect and Xcode  2 Purchase process itself on the device.  3 Verify the purchase and transaction.

slide 2:

Steps –  Step 1:- First start a new project  Step 2:- Select project targets and add the framework named StoreKit to your application.  NOTE: StoreKit does not work on the Simulator. You must test on a physical device.  Step 3:- ​import​ StoreKit/StoreKit.h in the class where you implement In-App Purchase.  Step 4:- Add StoreKit Delegate with interface as follows  interface ViewController :       UIViewControllerSKProductsRequestDelegateSKPaymentTransactionObserver  Step 5:-Now Update ViewController.h and your ViewController.xib as follows  Here we create reference for the SKProductsRequest UIActivityIndicatorView and connect the                       IBOutlets for Button.  In-App custom methods are user defined methods for start In-app Purchase.  ● voidfetchAvailableProducts​ Method fetches the product information we just added in  iTunes Connect. To access the product data we need to use the StoreKit  framework.here fetchAvailableProducts function used to fetch the available products  for In-app purchase.    ● BOOLcanMakePurchases​ Method returns a bool value to check the product  purchasable or not. The function canMakePayments is a static method of class  SKPaymentQueue and not a member function  ● IBActionpurchaseClicked:idsender​ IBAction Method start action when we press on  purchase button.  import​ UIKit/UIKit.h  import​ StoreKit/StoreKit.h  import​ “AppDelegate.h”  interface ViewController ​: UIViewControllerSKProductsRequestDelegateSKPaymentTransactionObserv er

slide 3:

// in-app purchase SKProductsRequest productsRequest NSMutableArray validProducts UIActivityIndicatorView activityIndicatorView IBOutlet UIButton purchaseButton UIAlertView purchaseAlert UIImageView Loaderimg // in-app custom method - voidfetchAvailableProducts - BOOLcanMakePurchases - voidpurchaseMyProduct:SKProductproduct - IBActionpurchaseClicked:idsender end Step 5:- Getting product information:  Before you can allow the user to purchase any products from your app you must send a request                                     to iTunes Connect to retrieve the list of available products or information from the server so                                 that they can notify to the user.  Step 6:- In your ViewController.m file define the IBAction as  IBActionpurchaseClicked:idsender LoaderimgUIImageView allocinitWithFrame:CGRectMake30 150 260 150

slide 4:

Loaderimg.backgroundColorUIColor grayColor Loaderimg.layer.cornerRadius5.0f activityIndicatorView UIActivityIndicatorView alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge activityIndicatorView setFrame:CGRectMakeLoaderimg.frame.size.width/2-20Loaderimg.frame.s ize.height/2 -20 3030 Loaderimg addSubview:activityIndicatorView activityIndicatorView startAnimating self.view addSubview:Loaderimg self fetchAvailableProducts Now you must be thinking what this code is doing… this method first initializes and loading view                                   for the user to tell him to wait till we fetches the product data.  activityIndicatorView UIActivityIndicatorView alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge This line initializes the activity indicator with style white large. You can read more about the                                 UIActivityIndicatorView class from here.   activityIndicatorView setFrame:CGRectMakeLoaderimg.frame.size.width/2-20Loaderimg.frame.s ize.height/2 -20 3030

slide 5:

This line tells the compiler to set this frame for the activityindicatorview that shows the waiting                                 view.  activityIndicatorView startAnimating  This line starts the animation in the view that tells user that the data is loading so please wait.  In the end of this method : self fetchAvailableProducts this line calls another method that we                                 will discuss later.  The method fetchAvailableProducts create a product request for productID and start the                         product request.  After that this StoreKit Delegate method called  -voidproductsRequest:SKProductsRequest request didReceiveResponse:SKProductsResponse response activityIndicatorView hidesWhenStopped SKProduct validProduct nil int count response.products count // NSLog"response "response.products objectAtIndex:0 if count0 validProducts NSMutableArray arrayWithArray:response.products validProduct response.products objectAtIndex:0 self purchase:Nil if validProduct.productIdentifier isEqualToString:kProductID

slide 6:

NSLog"response "validProduct.localizedTitle NSLog"response "validProduct.localizedDescription NSLog"response "validProduct.price else UIAlertView tmp UIAlertView alloc initWithTitle:"DemoPurchase" message:"No products to purchase" delegate:self cancelButtonTitle:nil otherButtonTitles:"Ok" nil tmp show Loaderimg removeFromSuperview purchaseButton.hidden NO

slide 7:

In this method passed the product request which is recently we create in                           fetchAvailableProducts and received the response from server and get the available product                         count.  If product count is greater then 0 then In-app purchase is done. By implementing the function  ● voidpaymentQueue:SKPaymentQueue queue updatedTransactions:NSArray  transactions   Step 7:- Now Update ViewController.m as follows.  Request the product and implement the delegate protocol for product request. voidpaymentQueue:SKPaymentQueue queue updatedTransactions:NSArray transactions  voidproductsRequest:SKProductsRequest request     didReceiveResponse:SKProductsResponse response  these are StoreKit delegates methods. import​ “ViewController.h”  define​ kProductID ”YourProductID”  define​ appDelegate AppDelegate UIApplication sharedApplication delegate  interface ViewController end implementation ViewController - voidviewDidLoad super viewDidLoad // Do any additional setup after loading the view typically from a nib.

slide 8:

-voidviewWillAppear:BOOLanimated validProducts NSMutableArray allocinit - voiddidReceiveMemoryWarning super didReceiveMemoryWarning // Dispose of any resources that can be recreated. - IBActionpurchaseClicked:idsender LoaderimgUIImageView allocinitWithFrame:CGRectMake30 150 260 150 Loaderimg.backgroundColorUIColor grayColor Loaderimg.layer.cornerRadius5.0f activityIndicatorView UIActivityIndicatorView alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge activityIndicatorView setFrame:CGRectMakeLoaderimg.frame.size.width/2-20Loaderimg.frame.s ize.height/2 -20 3030 Loaderimg addSubview:activityIndicatorView activityIndicatorView startAnimating

slide 9:

self.view addSubview:Loaderimg //Hide purchase button initially //purchaseButton.hidden YES self fetchAvailableProducts pragma ​ mark In-app custom -voidfetchAvailableProducts NSSet productIdentifiers NSSet setWithObjects:kProductIDnil productsRequest SKProductsRequest alloc initWithProductIdentifiers:productIdentifiers productsRequest.delegate self productsRequest start - BOOLcanMakePurchases

slide 10:

return SKPaymentQueue canMakePayments - voidpurchaseMyProduct:SKProductproduct if self canMakePurchases SKPayment payment SKPayment paymentWithProduct:product SKPaymentQueue defaultQueue addTransactionObserver:self SKPaymentQueue defaultQueue addPayment:payment else UIAlertView alertView UIAlertView allocinitWithTitle: "DemoPurchase" message:"Purchases are disabled in your device" delegate: self cancelButtonTitle:"Ok" otherButtonTitles: nil alertView show -IBActionpurchase:idsender NSLog"validProducts "validProducts self purchaseMyProduct:validProducts objectAtIndex:0

slide 11:

purchaseButton.enabled NO pragma ​ mark StoreKit Delegate -voidpaymentQueue: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:kProductID NSLog"Purchased " NSUserDefaults standardUserDefaults setObject:kProductID forKey:"ProductPurched" appDelegate.purchaseStateTRUE activityIndicatorView stopAnimating Loaderimg removeFromSuperview

slide 12:

NSUserDefaults standardUserDefaults synchronize purchaseAlert UIAlertView allocinitWithTitle: "DemoPurchase" message:"Purchase is completed succesfully" delegate: self cancelButtonTitle:"Ok" otherButtonTitles: nil purchaseAlert show SKPaymentQueue defaultQueue finishTransaction:transaction break case SKPaymentTransactionStateRestored: NSLog"Restored " SKPaymentQueue defaultQueue finishTransaction:transaction break case SKPaymentTransactionStateFailed: activityIndicatorView stopAnimating Loaderimg removeFromSuperview NSLog"Purchase failed " break default:

slide 13:

break -voidproductsRequest:SKProductsRequest request didReceiveResponse:SKProductsResponse response activityIndicatorView hidesWhenStopped SKProduct validProduct nil int count response.products count // NSLog"response "response.products objectAtIndex:0 if count0 validProducts NSMutableArray arrayWithArray:response.products validProduct response.products objectAtIndex:0 self purchase:Nil if validProduct.productIdentifier isEqualToString:kProductID NSLog"response "validProduct.localizedTitle NSLog"response "validProduct.localizedDescription NSLog"response "validProduct.price

slide 14:

else UIAlertView tmp UIAlertView alloc initWithTitle:"DemoPurchase" message:"No products to purchase" delegate:self cancelButtonTitle:nil otherButtonTitles:"Ok" nil tmp show Loaderimg removeFromSuperview purchaseButton.hidden NO end Step 8:- You have to update kProductID to the productID you created for your In-App Purchase.                                 You can add more than one product by updating the productIdentifiers’s NSSet in                           fetchAvailableProducts.   Step 9:- Now Run your App. Ensure you had logged out of your account in settings screen. Now                                     click on purchase button. Use Existing Apple ID. Enter your valid test account username and                               password. You will be shown the following alert in a few seconds.  Step 10:- Once your product is purchased successfully you will get the Purchase successful                             alert.

authorStream Live Help