How to Add In-App Purchases to an iOS App with StoreKit in Swift

Written by

in

Quick answer: To add in-app purchases, create the product in App Store Connect, add StoreKit.framework to your Xcode project, implement SKProductsRequestDelegate and SKPaymentTransactionObserver to fetch products and handle transactions, then test with a sandbox Apple ID.

Why this happens

In-app purchases require coordination between Apple’s servers, your App Store Connect configuration, and your app’s code. The root cause of most IAP failures is a mismatch between the product identifier registered in App Store Connect and the identifier used in your SKProductsRequest, or missing the StoreKit framework in the Xcode target. Apple also enforces that all purchase flows go through the SKPaymentQueue with a transaction observer, so skipping observer registration causes purchases to never complete.

How to fix it

1. Configure the product in App Store Connect

  1. Sign in to App Store Connect and select your app.
  2. Open Features → In-App Purchases and click +.
  3. Choose Non-Consumable (for permanent unlocks like “remove ads”) or Consumable (for repeatable items).
  4. Set a clear Reference Name for internal use.
  5. Enter a Product ID using reverse-DNS style, e.g., com.yourcompany.yourapp.removeads.
  6. Mark Cleared for Sale, pick a price tier (Tier 1 = $0.99), and add at least one localization with customer-facing title and description.
  7. Set Host Content with Apple to No unless you deliver Apple-hosted downloads.
  8. Save. Wait up to a few hours for the product ID to propagate to Apple’s servers.

2. Add StoreKit to your Xcode target

  1. Select the project navigator (blue icon), choose your app target, then General.
  2. Scroll to Frameworks, Libraries, and Embedded Content, click +, search for StoreKit.framework, and add it.
  3. If you’re in a pure Swift target, no bridging header is needed—just import StoreKit in your Swift files.

3. Implement the purchase manager

Create a singleton conforming to SKProductsRequestDelegate and SKPaymentTransactionObserver.

import StoreKit

final class IAPManager: NSObject {
    static let shared = IAPManager()
    private let removeAdsID = "com.yourcompany.yourapp.removeads"
    private var productsRequest: SKProductsRequest?
    private var completion: ((Result<Void, Error>) -> Void)?

    private override init() {}

    func purchaseRemoveAds(completion: @escaping (Result<Void, Error>) -> Void) {
        self.completion = completion
        guard SKPaymentQueue.canMakePayments() else {
            completion(.failure(IAPError.paymentsDisabled))
            return
        }
        let request = SKProductsRequest(productIdentifiers: [removeAdsID])
        request.delegate = self
        request.start()
        productsRequest = request
    }

    func restorePurchases(completion: @escaping (Result<Void, Error>) -> Void) {
        self.completion = completion
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().restoreCompletedTransactions()
    }
}

// MARK: - SKProductsRequestDelegate
extension IAPManager: SKProductsRequestDelegate {
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        guard let product = response.products.first else {
            completion?(.failure(IAPError.productNotFound))
            return
        }
        let payment = SKPayment(product: product)
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().add(payment)
    }

    func request(_ request: SKRequest, didFailWithError error: Error) {
        completion?(.failure(error))
    }
}

// MARK: - SKPaymentTransactionObserver
extension IAPManager: SKPaymentTransactionObserver {
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case .purchased, .restored:
                completeTransaction(transaction)
            case .failed:
                failTransaction(transaction)
            case .deferred, .purchasing:
                break // wait for final state
            @unknown default:
                break
            }
        }
    }

    private func completeTransaction(_ transaction: SKPaymentTransaction) {
        SKPaymentQueue.default().finishTransaction(transaction)
        SKPaymentQueue.default().remove(self)
        // Persist unlock (e.g., UserDefaults, Keychain, or server receipt validation)
        UserDefaults.standard.set(true, forKey: "adsRemoved")
        completion?(.success(()))
    }

    private func failTransaction(_ transaction: SKPaymentTransaction) {
        SKPaymentQueue.default().finishTransaction(transaction)
        SKPaymentQueue.default().remove(self)
        let error = transaction.error ?? IAPError.unknown
        completion?(.failure(error))
    }
}

enum IAPError: Error {
    case paymentsDisabled
    case productNotFound
    case unknown
}

4. Hook up UI and start the flow

@IBAction func removeAdsTapped(_ sender: UIButton) {
    IAPManager.shared.purchaseRemoveAds { [weak self] result in
        DispatchQueue.main.async {
            switch result {
            case .success:
                self?.showAlert(title: "Success", message: "Ads removed!")
            case .failure(let error):
                self?.showAlert(title: "Failed", message: error.localizedDescription)
            }
        }
    }
}

@IBAction func restoreTapped(_ sender: UIButton) {
    IAPManager.shared.restorePurchases { [weak self] result in
        DispatchQueue.main.async {
            switch result {
            case .success:
                self?.showAlert(title: "Restored", message: "Purchases restored.")
            case .failure(let error):
                self?.showAlert(title: "Failed", message: error.localizedDescription)
            }
        }
    }
}

5. Test with a Sandbox account

  1. In App Store Connect → Users and Access → Sandbox, create a new tester Apple ID.
  2. On your test device, sign out of your real Apple ID in Settings → App Store.
  3. Run the app on a physical device (StoreKit does not work in the simulator for purchases).
  4. When prompted, sign in with the sandbox tester credentials.
  5. Verify the purchase flow completes and UserDefaults.standard.bool(forKey: "adsRemoved") returns true.

How to prevent it

  • Match product IDs exactly — copy the Product ID from App Store Connect into your code; a single typo makes productsRequest return zero products.
  • Add the transaction observer early — call SKPaymentQueue.default().add(observer) before any purchase starts, ideally in application(_:didFinishLaunchingWithOptions:) for production apps.
  • Finish every transaction — always call finishTransaction(_:) in both .purchased and .failed cases, otherwise the queue retries indefinitely.
  • Validate receipts server-side for non-consumables and subscriptions to prevent receipt spoofing.
  • Test on device only — the simulator cannot complete StoreKit purchases.

FAQ

Why does productsRequest return an empty products array?

The product ID in your code doesn’t match the one in App Store Connect, the product isn’t “Cleared for Sale,” or the agreement/tax/banking setup in App Store Connect is incomplete. Wait a few hours after creation for propagation.

Can I test in-app purchases in the iOS Simulator?

No. StoreKit requires a real device signed in with a sandbox Apple ID. The simulator will always return “Cannot connect to iTunes Store” or empty product lists.

Do I need a bridging header for StoreKit in a Swift project?

No. StoreKit is a system framework with full Swift module maps. Just import StoreKit and use the native Swift APIs shown above.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.