In App Purchases in iOS applications with Swift

Implement In App Purchase (IAP) in iOS applications [swift]

Now a days, most of the application provide the option to get the extra feature or content by making purchase 🙂. This process is well known as In App Purchase (IAP), is a great way to earn the money 💰 from your iOS or MacOS applications. 
Yes, It’s a unquestionable fact that mainly developer’s (Apple’s of course) revenue is based on the In App Purchases 😯. Like it or not 🤨, Apple charge 30% for each successful transaction that your application will make 😲.

So, today we are going to discuss about the In App Purchases and see the process of integrating In App Purchase in iOS application with Swift 4.0 language.

Types Of In App Purchases:

When user make any IAP to buy extra content of subscription, make one of these in app purchase:

  1. Consumable: User will need to buy these items every time, as want to use them, can not be used in future for free. On reinstalling, changing device user might lose their consumable products. For example, buying game currency, health and hints etc.
  2. Non-consumable: User buy these item one time, can be used in future for free. On reinstalling, changing device these products will not be lost. If user lose, might be able to download it again for free by restore in-app purchases. For example: upgrading app to pro version, removing ads etc.
  3. Non-renewing subscriptions: User will be able to use these items for a fixed period of time, these items can be purchase again after the subscription end. For example: a sport session pass for one, three, or six moths.
  4. Auto-renewable subscriptions: User can buy these item for a specified period of time, It’ll automatically renew when the period has passed. For example: Ongoing services (Netflix, Hulu Plus, etc.), Magazine subscriptions etc.

We will try to cover all the thing that are need to implement IAP in iOS application, will be discuss on the following topics in this:

  1. iTunes Connect Setup
  2. The Code in Swift
  3. Using the code
  4. Testing the IAP

1. iTunes Connect Setup:

We will discuss this part in four section: Setup bank account, Sandbox user creation, iTunes app creation and IAP products creation.

Setup Bank Account:

If you don’t have the bank account setup in your iTunes connect account, will not be able to use IAP services ❗. So, it’s a most important part to get the IAP services work. We can do it by going to the Agreements, Tax and Banking section of iTunes connect account. It should look something like this:

Sandbox User Creation:

Now, we need to create a sandbox user, to create navigate to Users and Roles in iTunes connect account and choose the Sandbox Testers section. It is very important to add sandbox user to test the IAP services, by sandbox user you can make transactions for free.

📣 Always remember to use an email that is not accosted with any Apple ID.

iTunes App Creation:

To create an application on iTunes to to My Apps section of iTunes connect account, or use an existing app that you already have. In order to create an application on iTunes you have to create an App Id from you developer account.

IAP Products Creation:

In order yo create IAP Products, open your iTunes application and navigate to the Features section. Click on the “+” button and choose one of the 4 types that we have already discussed. Then provide all the required metadata related to that IAP Product. Pay attention to the Product Id.

Product Id should be unique and understandable, we will be needing these product IDs to get the desired IAP products.
Here are some examples of IAP products that I have created.

So, here we are done with the first step towards integrating IAP. Let’s proceed to the next step that is code.

Oh Yeah!! I made it.

2. The Code in Swift:

Keep the code in a separate class that I have created PKIAPHandler, feel free to change the name if you don’t like it 😋. We will be storing all the things related to In App Purchase in this class. 
So, let’s discuss the code. What this class contains.

Properties:

Firstly you need to store all the usable IAP products Ids in an array, where you are going to show all the create IAP products (in step IAP Products Creation) in you application to show the user.
There is a property `isLogEnabled` it’ll help you to enable the console log of the PKIAPHandler. 
`shared` property will let you interact with all the member functions that you need to use while IAP services. 
For the better understanding I’ve attached the GIST file of the code. Scroll down 👇🏻 to have a look on it.

Class Functions:

  1. canMakePurchases(): return a bool value (true/false) either the device is able to make purchase or not.
  2. setProductIds(ids: [String]): Use this methods to set the IAP product Ids to working with. Call this methods in viewDidLoad method of your UIViewController in which you are going to show the available IAP products.
  3. fetchAvailableProducts(complition: @escaping (([SKProduct])->Void)): Use this method to fetch all the IAP product details for the IDs that you have set by setProductIds method. It’ll return an array of SKProduct, this SKProduct object will have all the details that you entered while creating IAP products on iTunes. Get this array and keep it in an array for showing in listing and to be used in future for making purchase.
  4. purchase(product: SKProduct, complition: @escaping ((PKIAPHandlerAlertType, SKProduct?, SKPaymentTransaction?)->Void)) : Use this method to initiate purchase for the product (user the SKProduct that you have all-ready fetched by fetchAvailableProducts method). It’ll raise the payment dialog box for the user confirmation. In completion block, you will get message from handler, product that purchased and payment transaction details if purchased successfully otherwise product and payment transaction will be nil.
  5. restorePurchase(): Use this method to restore the purchase for the purchased/non-consumable item.

Delegate Methods:

  1. productsRequest (_ request:SKProductsRequest, didReceive response:SKProductsResponse): returns all the IAP products that are available on the iTunes with respect to the IDs that you have set by setProductIds method. It’ll get triggred just after calling the fetchAvailableProducts method.
  2. paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue): Handles a situation where a user successfully restores an IAP product.
  3. paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]): This delegate methods triggered just after calling the purchase(product: SKProduct) method. In this method, you will get all details related to IAP transaction either item purchased or failed.

3. Using The Code:

Open you UIViewController, create an empty array of type SKProduct, then in viewDidLoad function set the IAP products IDs and fetch all the IAP products detail and show them either in UITableView, UICollectionView or as you want.

PKIAPHandler.shared.setProductIds(ids: self.productIDs)
PKIAPHandler.shared.fetchAvailableProducts { [weak self](products)   in
   guard let sSelf = self else {return}
   sSelf.productsArray = products
   sSelf.tableView.reloadData() //reload you table or collection view
}

The either create an action or use didSelect delegate method of tableView/collectionView to initiate the IAP Purchase by calling purchase() method.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
PKIAPHandler.shared.purchase(product: self.productsArray[indexPath.row]) { (alert, product, transaction) in
   if let tran = transaction, let prod = product {
     //use transaction details and purchased product as you want
   }
   Globals.shared.showWarnigMessage(alert.message)
   }
}

Here is the code file, scroll down 👇🏻 to look over it.

We are done here for implementing the IAP in iOS application with swift. 
Now, Let’s go for testing.

Let’s go for testing

4. Testing:

Firstly, sign-in to your iOS device using the created Sandbox user account, then run your application on the real device and initiate the transaction. Don’t worry about the price that are being displayed in the Alert window just go further. Nothing will be charged 🤩 as you are sandbox user for the application.

📜 Note: In App Purchases can not be tested on iOS simulator. So, Please use real device.

👩‍💻 !!! HAPPY CODING !!! 👨‍💻

Thank you for reading, please hit the recommend icon if like this collection 😊 . Questions? Leave them in the comment.