iOS Development
In-App Purchase
App Store
Programming
Swift

How do you add an in-app purchase to an iOS application?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Adding in-app purchases to an iOS application is a great way to monetize your app. In-app purchases allow you to sell a variety of content or services directly within your app, such as subscriptions, new features, or additional content. This guide will walk you through the step-by-step process of integrating in-app purchases into an iOS application using Apple's StoreKit framework.

Prerequisites

Before you start, ensure the following:

  • You have a valid Apple Developer account.
  • Your iOS app is set up on Xcode.
  • You have a basic understanding of Swift programming.
  • Your app's App ID is configured in your Apple Developer account.

Step-by-Step Process

1. Configure Your App in App Store Connect

  1. Create an App Record:
    • Log in to your App Store Connect account.
    • Navigate to "My Apps" and create a new app or select an existing app record.
  2. Set Up In-App Purchase:
    • Within your app record, go to the "Features" tab.
    • Click on "In-App Purchases" and add a new in-app purchase by selecting one of these types:
      • Consumable
      • Non-consumable
      • Auto-renewable subscription
      • Non-renewing subscription
  3. Add In-App Purchase Details:
    • Define the product ID (unique within your app).
    • Add localized titles and descriptions.
    • Set the pricing tier.
    • Submit for review, ensuring all assets and details are complete.

2. Integrate StoreKit in Your Xcode Project

  1. Import StoreKit Framework:
    • Open your Xcode project.
    • Add the StoreKit framework to your project by selecting your target, going to the "General" tab, and ensuring StoreKit appears under "Linked Frameworks and Libraries".
  2. Request Product Information:
    • Use SKProductsRequest to fetch information about your products from Apple's server.
swift
1   import StoreKit
2
3   class StoreManager: NSObject, SKProductsRequestDelegate {
4       private var productRequest: SKProductsRequest?
5
6       func fetchProducts(productIdentifiers: Set<String>) {
7           productRequest?.cancel()
8           productRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
9           productRequest?.delegate = self
10           productRequest?.start()
11       }
12
13       func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
14           let products = response.products
15           for product in products {
16               print("Product: \(product.localizedTitle), \(product.price)")
17           }
18       }
19   }
  1. Handle Transactions:
    • Implement the SKPaymentTransactionObserver to update your app's UI and functionalities based on the transaction statuses.
swift
1   extension StoreManager: SKPaymentTransactionObserver {
2       func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
3           for transaction in transactions {
4               switch transaction.transactionState {
5               case .purchased:
6                   // Handle when purchase is successful
7                   complete(transaction: transaction)
8               case .failed:
9                   // Handle when purchase is failed
10                   failed(transaction: transaction)
11               case .restored:
12                   // Handle when previous purchase is restored
13                   restore(transaction: transaction)
14               default:
15                   break
16               }
17           }
18       }
19
20       private func complete(transaction: SKPaymentTransaction) {
21           // Unlock features for user
22           SKPaymentQueue.default().finishTransaction(transaction)
23       }
24
25       private func failed(transaction: SKPaymentTransaction) {
26           if let error = transaction.error as NSError? {
27               print("Transaction Error: \(error.localizedDescription)")
28           }
29           SKPaymentQueue.default().finishTransaction(transaction)
30       }
31
32       private func restore(transaction: SKPaymentTransaction) {
33           // Restore previous purchases
34           SKPaymentQueue.default().finishTransaction(transaction)
35       }
36   }
  1. Add Payment to Queue:
    • Add the payment to the queue when the user initiates a purchase.
swift
1   func purchase(product: SKProduct) {
2       let payment = SKPayment(product: product)
3       SKPaymentQueue.default().add(payment)
4   }
  1. Restore Purchases:
    • Provide a way for users to restore purchases, commonly via a "Restore Purchases" button.
swift
   func restorePurchases() {
       SKPaymentQueue.default().restoreCompletedTransactions()
   }

3. Testing In-App Purchases

  • Use Sandbox Testing:
    • Create a sandbox test user in App Store Connect.
    • Sign out of the App Store on your device and sign in with your sandbox account to test purchasing in your development environment.
  • Understand Edge Cases:
    • Test scenarios like cancelled transactions, failed transactions, and network interruptions.

4. Submission and Review

  • Upload Your App:
    • Ensure your in-app purchase products are approved.
    • Submit your app for review with the in-app purchases.
  • Provide Tester Information:
    • Add detailed testing instructions during app submission for easier review by Apple.

Summary Table

StepDescription
Configure AppSet up app and in-app purchases in App Store Connect
Integrate StoreKitAdd StoreKit framework and implement purchase logic
Transaction HandlingManage purchase success, failure, and restoration
Purchase InitiationAdd payments to SKPaymentQueue upon user action
TestingUse sandbox accounts for testing purchase functionalities

Conclusion

Integrating in-app purchases involves careful setup and rigorous testing. By following these steps and implementing required features, you can successfully add in-app purchases to your iOS app, enhancing user experience and generating revenue. Remember to consult Apple's detailed guidelines and ensure compliance with their terms to avoid rejection during app review.


Course illustration
Course illustration

All Rights Reserved.