iOS in-app purchases: Initialization and purchases processing
10 min read
Share
We continue our series of articles dedicated to iOS in-app purchases. In the previous part, we have discussed the process of creating in-app purchases and their configuration. Now we are going to show you how to create a simple paywall (payment screen) as well as how to initialize and process purchases that we have configured.
Creating a subscription screen
Any app that uses in-app purchases has a paywall. There are some guidelines from Apple that determine must-have elements. At this step, we’ll implement just some of them to give you a sense of that to do next.
Paywall example
So, our screen will have the following:
Header with premium description;
Subscription activation buttons with local currency and title;
Restore purchases button. This element is necessary for all the applications that use subscriptions or non-consumable purchases.
I've used Interface Builder Storyboard for layout, but you can use just coding. I've also moved UIActivityIndicatorView to ViewController to present payment process.
Show purchase information
Let's build a core of our ViewController. It doesn't have any logic and we full fill it's later.
Property class fields to link UI elements with our code.
Launching asynchronous initialization process of purchases unit in viewDidLoad(). To make this process independent from the UI layer, it’s better to call it just right after the app launch. It this article, to make it easier let's do it just right in ViewController.
Before launching the initialization, we'll show the loading bar and we'll remove it after initialization finishes. I’ve written some helper functions for it, check them below.
updateInterface() function that updates UI with purchase data such as trial duration and pricing.
Buttons handlers for initialization and purchase restoration.
Pay attention to the usage (1) of SKProduct objects. We make an extension to easily extract the information. This implementation is more flexible then using SKProduct props directly:
extension SKProduct {
var localizedPrice: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = priceLocale
return formatter.string(from: price)!
}
var title: String? {
switch productIdentifier {
case “barcode_month_subscription”:
return “Monthly Subscription”
case “barcode_year_subscription”:
return “Annual Subscription”
default:
return nil
}
}
}
Purchases unit
I’ve slightly refined the Purchases class to make it possible to show the result of an asynchronous operation in the interface. I also cached SKProduct objects for further usage.
Let's add Errors handling to our code. I created enum PurchaseError to implement Error protocol (or LocalizedError):
enum PurchasesError: Error {
case purchaseInProgress
case productNotFound
case unknown
}
All errors on StoreKit level will be caught as a single error, get more information about the error types in the documentation.
purchaseProduct() function launches the purchase process of the selected product, and restorePurchases() function requests the list of the users' purchases from the system: auto renewable subscriptions or non-consumable purchases:
Iterate on transaction body, processing each one individually
In case the transaction is in purchased or restored status, we need to do all the necessary actions to make the content/subscription available for the user. Then we need to close the transaction with finishTransaction method. Important: if you work with consumable purchases it’s crucially important to ensure that the user has gained access to the content and close the transaction right after the check. Otherwise, it’s possible to lose the information about the purchase.
The purchase process may finish with an error due to different reasons, return this information.
We provide the user with the purchased content in the function that we request on step 2: (for example, we remember the subscription expiry date for UI to interpret the user as premium)
In this case, we have discussed some of the existent transaction statuses. There is also purchasing status (it means the transaction is being processed) and deferred status means the transaction is postponed indefinitely and will be finished later (for example, while waiting for the confirmation from parents). These statuses can be shown in UI if necessary.
Call in the interface
The core part is done, so we just need to call execute these functions in the ViewController.
@IBAction func purchaseAPressed(_ sender: UIButton) {
showSpinner()
Purchases.default.purchaseProduct(productId: “barcode_month_subscription”) {
[weak self] _ in
self?.hideSpinner()
// Handle result
}
}
@IBAction func purchaseBPressed(_ sender: Any) {
showSpinner()
Purchases.default.purchaseProduct(productId: “barcode_year_subscription”) {
[weak self] _ in
self?.hideSpinner()
// Handle result
}
}
@IBAction func restorePressed(_ sender: UIButton) {
showSpinner()
Purchases.default.restorePurchases {
[weak self] _ in
self?.hideSpinner()
// Handle result
}
}
This is it. In the next part, we will discuss the basic ways to test the purchase mechanism, and how to design paywall to pass a review for the App Store.