Build With RevenueCat

Build a customized mobile subscription business with RevenueCat. We do the heavy lifting of normalizing subscribers from any source and maintain a single source of truth for subscription status, so you can get back to building your app.

RevenueCat is a powerful, secure, reliable, and free to use in-app purchase server with global support. All you need to get started is an API key.

Get Started    API Reference

SwiftUI App Lifecycle

Initializing the Purchases SDK in SwiftUI

With the next iteration of SwiftUI announced at WWDC 2020, entire apps can be created with just a simple struct conforming to the new App protocol, like so:

@main
struct SampleApp: App {    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Without traditional delegate methods commonly used to initialize the SDK, it can seem a little confusing as to where the Purchases SDK should be initialized.

Option 1: App Init

For basic initialization without delegate methods, you can implement the App init method:

import Purchases

@main
struct SampleApp: App {
    init() {
        Purchases.configure(withAPIKey: "api_key")
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Option 2: App Delegate

Another method of initialization is to use the new @UIApplicationDelegateAdaptor property wrapper to configure the Purchases SDK. The @UIApplicationDelegateAdaptor gives the option of using UIApplicationDelegate methods that are traditionally used in UIKit applications.

Creating a Delegate

Begin by creating a delegate class and initializing the Purchases SDK like the following:

import Purchases

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        Purchases.debugLogsEnabled = true
        Purchases.configure(withAPIKey: "api_key")
        return true
    }
}

Attaching the Delegate

As previously mentioned, the new @UIApplicationDelegateAdaptor property attaches the delegate to the new SwiftUI App struct. Add the property wrapper like the following:

@main
struct SampleApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Build and run the app, and Purchases will be initialized on app launch.

For more information on configuring the Purchases SDK, check out the Configuring SDK guide.

Updated 20 days ago


SwiftUI App Lifecycle


Initializing the Purchases SDK in SwiftUI

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.