← Back to Tutorials

12. Monetization

Networking & Communication

In-App Purchases (StoreKit)

Offer digital goods and subscriptions using StoreKit 2:

import StoreKit

// Fetch products
let products = try await Product.products(
    for: ["com.example.premium"])

// Purchase
if let product = products.first {
    let result = try await product.purchase()
    switch result {
    case .success(let verification):
        let transaction = try verification.payloadValue
        // Unlock premium content
        await transaction.finish()
    case .pending:
        print("Waiting for approval")
    case .userCancelled:
        print("User cancelled")
    @unknown default:
        break
    }
}

// Check entitlement
for await result in Transaction.currentEntitlements {
    if case .verified(let transaction) = result {
        if transaction.productID == "com.example.premium" {
            // User has premium
        }
    }
}

Subscriptions

Auto-renewable subscriptions generate recurring revenue:

// Subscription product IDs
let subscriptionIDs = [
    "com.example.monthly",
    "com.example.yearly"
]

// StoreKit handles subscription status automatically
// Use Transaction.currentEntitlements to check status
for await result in Transaction.currentEntitlements {
    if case .verified(let transaction) = result {
        if transaction.revocationDate == nil {
            // Subscription is active
        }
    }
}

AdMob / Google Ads

Display banner, interstitial, and rewarded ads via Google Mobile Ads SDK:

import GoogleMobileAds

// Banner ad
let banner = GADBannerView(adSize: GADAdSizeBanner)
banner.adUnitID = "ca-app-pub-xxxxxxxx/yyyyyy"
banner.rootViewController = self
banner.load(GADRequest())

// Interstitial ad
let interstitial = GADInterstitialAd(
    adUnitID: "ca-app-pub-xxxxxxxx/zzzzzz")
interstitial.delegate = self
// Show when ready
if interstitial.isReady {
    interstitial.present(fromRootViewController: self)
}

App Analytics

Track usage and revenue with App Store Connect Analytics, Google Analytics, or Firebase:

// Firebase Analytics
Analytics.logEvent("purchase_completed", parameters: [
    "product_id": "premium",
    "value": 9.99,
    "currency": "USD"
])
Practice Task: Set up StoreKit in a test app with one consumable product (e.g., "5 Coins" for $0.99) and one auto-renewable subscription ("Premium Monthly" at $4.99). Test the purchase flow using StoreKit Testing in Xcode. Display the purchase state in the UI and persist it using UserDefaults or Keychain.