📦 SwiftyLaunch Modules
💰 InAppPurchaseKit
Lock Views behind a Paywall

Lock SwiftUI Views behind a Paywall

InAppPurchaseKit (SwiftyLaunch Module) - Lock Views behind a Paywall

If you want to lock specific views behind a paywall in SwiftUI, we provide a special view modifier that allows you to do just that.

The .requirePremium() View Modifier

You can use the .requirePremium() view modifier to lock a view behind a paywall. Simple as that.

import SwiftUI
import InAppPurchaseKit
 
struct ContentView: View {
 
    @EnvironmentObject var iap: InAppPurchases
 
    var body: some View {
        // This view will only be shown if the user is the user has premium access
        // Otherwise, it will show a paywall
        Text("Premium Text")
            .requirePremium(iap: iap)
    }
}

View Modifier definition:

extension View {
    public func requirePremium(iap: InAppPurchases, onCancel: @escaping () -> Void = {}) -> some View {}
}
  • iap - The InAppPurchases object that is used to check if the user has premium access. Accessed through the @EnvironmentObject property wrapper.
  • onCancel - (Optional) action to perform when the user cancels the paywall.

Implementation Example

As an example to demonstrate the usage of the .requirePremium() view modifier, we have created a settings view that allows users to change their app icon, but only if they have premium access. It can be found in the Settings Tab → Appearance.

Example

AppearanceView.swift
import InAppPurchaseKit
 
struct AppearanceView: View {
 
    @EnvironmentObject var iap: InAppPurchases
 
    // Passed from parent to pop back to the root view in the navigation stack
    let popBackToRoot: () -> Void
 
     var body: some View {
        List {
            Section(header: Text("App Icon")) {
                // ...
            }
        }
        .navigationTitle("App Appearance")
        .requirePremium(iap: iap, onCancel: popBackToRoot)
     }
}