paint-brush
[SWIFT] How to add In-App Purchases in your iOS appby@dejanatanasov
32,035 reads
32,035 reads

[SWIFT] How to add In-App Purchases in your iOS app

by Dejan AtanasovJuly 16th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<a href="https://support.apple.com/en-us/HT202023" target="_blank">In-app purchase (IAP)</a> is a great way to earn money from your iPhone, iPad, iPod touch or Mac app. You can detect if some app offers <a href="https://hackernoon.com/tagged/iap" target="_blank">IAP</a> by going to the app page, and see if it has “Offers In-App Purchases” or “In-App Purchases” near the Price, Buy, or Get button. IAP is mostly used to unlock some extra content in your app that you want to monetize from. Like it or not, Apple charges 30% of each successful transaction that your app will make.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - [SWIFT] How to add In-App Purchases in your iOS app
Dejan Atanasov HackerNoon profile picture

Introduction

In-app purchase (IAP) is a great way to earn money from your iPhone, iPad, iPod touch or Mac app. You can detect if some app offers IAP by going to the app page, and see if it has “Offers In-App Purchases” or “In-App Purchases” near the Price, Buy, or Get button. IAP is mostly used to unlock some extra content in your app that you want to monetize from. Like it or not, Apple charges 30% of each successful transaction that your app will make.

Examples of IAP:

  • In a photography app you can buy extra effects for x.xx$;
  • Open the Medium iOS app and you can see a "Become a member" button under Settings, which offers a monthly subscription with lots of premium content;
  • Buy coins or other virtual currency in a game, so you can progress faster.

The 4 types of IAP:

  1. Consumable - the user needs to buy these items every time he wants them. Examples of consumable purchases are buying game currency, hints, health etc.
  2. Non-Consumable - once you buy this, you will have it forever. This is a one time purchase, and you can also transfer it between devices connected with the same AppleID. Examples are: upgrading an app to pro version, removing ads, city guide maps etc.
  3. Non-renewing subscriptions - using the app content for a fixed period of time, and you can buy it again after it ends. For example, a sports season.
  4. Auto-renewing subscriptions - you can subscribe to the content or the services that the app is offering for a specific period. It will automatically renew when the period has passed. Examples, newspaper subscriptions, Netflix, games, etc.

With this tutorial, you will learn everything that you need to know about In-App Purchases. I will try to be as much detailed as possible, and will break down this tutorial to multiple steps for better understanding:

  1. iTunes Connect Setup
  2. The Code
  3. Using the Code
  4. Testing

1. iTunes Connect Setup

Enter your bank account details

The most important part to get the IAP work is to enter your bank information. That can be done by going to the Agreements, Tax, and Banking section in iTunes Connect. If you don't have this setup, you can't use the IAP services. Should look something like this below…

Create a Sandbox User

Then we need to create a Sandbox User. To create this kind of user navigate to Users and Roles and choose the Sandbox Testers section. Remember to use an email that isn't associated with any Apple ID. You will need the Sandbox User to create test payments, otherwise, you can't test them.

Create an iTunes App

Go to the My Apps section and create an app. Or, use an existing app if you already have one. To create an app you will have to create an App ID from your Developer account.

Create the IAP products

Click on your iTunes app and navigate to the Features section. There you can create a new IAP product. Click on the + icon and pick one of the 4 types that I have explained you above. Then enter the required metadata related to that IAP. Pay attention to the Product ID, as you will need that identifier in your app to call the desired IAP. Here is how it should look like.

Here are some examples of IAP's that I have created. The warnings are completely normal.

We are done with the iTunes Connect setup. If you are clear, then let's proceed to the next step where I will explain you the code.

2. The Code

Keep the code in a separate class. I have named mine IAPHandler, but feel free to change the name if you don't like it. In this class, we will store everything related to In-App Purchases. For a better understanding, I will attach the whole GIST file and will explain each function in the file…

Variables

The first thing that you need to do is to create variables from your IAP product ID's (in my case CONSUMABLE_PURCHASE_PRODUCT_ID and NON_CONSUMABLE_PURCHASE_PRODUCT_ID). Also, we will create variables for handling the IAP request and an array that will store all the available IAP products.

Class functions

  1. canMakePurchases() — returns a boolean value whether the device is able to make purchases or not.
  2. purchaseMyProduct(index: Int) —use this function for initiating a purchase. This function will raise the payment dialog. Send index to get the correct IAP product from the iapProducts array.
  3. restorePurchase() — function for restoring the IAP. Used if the user changes a device, and he already owns a non-consumable IAP in your app.
  4. fetchAvailableProducts() — Create a collection of product ID's that you want to use, by adding all of them into an NSSet object. Remember to set the delegate method, so you can get the SKProduct results back.

Delegate Methods

  1. productsRequest (_ request:SKProductsRequest, didReceive response:SKProductsResponse) — returns all the available In-App Purchases and populates the iapProducts array. Triggered after calling the fetchAvailableProducts() function.
  2. paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) — handles a situation where a user successfully restores an IAP.
  3. paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) — this delegate method is triggered after calling the purchaseMyProduct(index: Int) function**.** In this callback, you will get everything related to the IAP transaction ( like if an item has been purchased or it failed).

Callback handler

As a bonus, I have added the callback handling enum. Create a closure purchaseStatusBlock(), which returns various IAP transaction statuses for more clearer code. To make it even better, I have created an enum type called IAPHandlerAlertType, which will return a message for the suitable case.

Scroll below the GIST file to discover how to use this class.

3. Using the Code

Go to your UIViewController and then in your in viewDidLoad() function, fetch the products and also add the closure where you will get the response of the transaction that the user has made.

IAPHandler.shared.fetchAvailableProducts()

IAPHandler.shared.purchaseStatusBlock = {[weak self] (type) in            guard let strongSelf = self else{ return }            if type == .purchased {                let alertView = UIAlertController(title: "", message: type.message(), preferredStyle: .alert)                let action = UIAlertAction(title: "OK", style: .default, handler: { (alert) in                                    })                alertView.addAction(action)                strongSelf.present(alertView, animated: true, completion: nil)            }        }

Then create an action where you will initialize the transaction window. The below example will get the first product from the iapProducts array.

@IBAction func consumable(btn: UIButton){    IAPHandler.shared.purchaseMyProduct(index: 0)}

4. Testing

Sign In with your Sandbox User on your iOS device, navigate to your app and click the action to initiate the transaction. Don't worry about the price on the transaction window. Since you are using a Sandbox User, nothing will be charged from your account.

NOTE: You can't test In-App Purchases on iOS Simulator. Please use a real device.

That’s it from this tutorial and if it helped you please 👏 or share this story so others like you can find it. Thank you for your attention! 🚀

Check out my latest project:


‎VIP Sports Bet Tips & Scores on the App Store_This app is only available on the App Store for iOS devices. Increase your profits by following our professional BET…_apple.co

Read more of my writing on Medium:


Introducing Clean Swift Architecture (VIP)_Forget MVC, now!_hackernoon.com


Your ultimate guide to the Google Maps SDK on iOS, using Swift 4_Many iOS apps use Google Maps. This is a very common feature, so I have decided to prepare an ultimate guide on the…_medium.freecodecamp.org


SWIFT — Custom UIView with XIB file_Custom UIView with XIB file is a very common practice in iOS Development. Custom UIView classes don’t contain XIB files…_medium.com


How to add Spotlight support to your iOS app_A Swift tutorial that will make your app available in Spotlight search_hackernoon.com


Core Data Relationships_Understanding One-to-One and One-To-Many relationships_hackernoon.com


Understanding Auto Layout in Xcode 9_All you need to know about Auto Layout_hackernoon.com

Subscribe to my Newsletter: