horse revenue Docs

SDK reference

iOS API reference

Every public type and call in the Horse iOS SDK 2.0.0, with its documentation, generated from the source of horsekit-ios. For how to use them together, start with the tutorial and the guides.

<!-- Generated by website/scripts/sdk-reference.mjs from horsekit-ios 2.0.0. Don't edit by hand: run npm run sdk-reference in website/. -->

#HorseKit

The core every app adds: purchases, entitlements, offerings, remote config, experiments, access codes and analytics. import HorseKit

#HorseDelegate

Delegate for UIKit-style consumers; SwiftUI apps can observe customerInfo instead.

public protocol HorseDelegate: AnyObject

#Horse

The Horse Revenue SDK entry point — a RevenueCat-shaped facade over StoreKit 2 + the Horse Revenue API.

Horse.configure(apiKey: "pk_…", appUserID: firebaseUid)      // at launch
let offerings = try await Horse.shared.offerings()
let result = try await Horse.shared.purchase(package: offerings.current!.monthly!)
if Horse.shared.customerInfo?.isEntitled("pro") == true { unlock() }
public final class Horse: ObservableObject
public enum RestorePolicy: String, Sendable

How previously-owned Apple purchases reach a customer. See Configuration.restorePolicy.

public enum Analytics: String, Sendable

Whether the SDK records product analytics at all.

public enum ScreenTracking: String, Sendable

Where screen names come from.

public enum StartPolicy: Sendable, Equatable

Whether the SDK reaches the network by itself, or only when the app asks.

public struct Configuration: @unchecked Sendable
public var apiKey: String
public var appUserID: String?
public var baseURL: URL
public var logLevel: HorseLogLevel
public var finishTransactions: Bool

Finish transactions after a successful server sync (default). Set false if the app delivers content itself and calls finish() on its own.

public var restorePolicy: RestorePolicy

What to do about purchases the Apple ID already owns when this app user id has never been seen with them (a reinstall, a new anonymous id, a second device):

  • .onRestore (default): nothing happens until the user taps Restore Purchases (or buys), or the app calls syncPurchases() itself (silent). Entitlements follow your app user id, so a fresh install starts locked and the paywall is testable. This is how the app behaved with RevenueCat.
  • .automatic: the SDK claims them silently at launch. Convenient, but a reinstall unlocks itself and you can never see the paywall again on that device.

Purchases made in this install — and renewals of them — are always recognised immediately, in both modes.

public var startPolicy: StartPolicy

When the SDK may reach the network. Default .automatic.

public var userDefaults: UserDefaults
public var analytics: Analytics

On by default — the paywall funnel is the reason the SDK exists next to StoreKit — and .off sends nothing at all, not even a session.

public var screenTracking: ScreenTracking

How screens are named. .automatic swizzles UIViewController.viewDidAppear and uses the class name; SwiftUI needs .horseScreen("…") either way, since one hosting controller is the whole app.

public init(apiKey: String, appUserID: String? = nil, baseURL: URL, logLevel: HorseLogLevel = .warn, finishTransactions: Bool = true, restorePolicy: RestorePolicy = .onRestore, startPolicy: StartPolicy = .automatic, userDefaults: UserDefaults = .standard, analytics: Analytics = .on, screenTracking: ScreenTracking = .manual)
public static let customerInfoDidChangeNotification
public static let remoteConfigDidChangeNotification
public static var shared: Horse

The configured instance. Usable from any thread (like Purchases.shared); its mutable state lives on the main actor, its async methods can be awaited from anywhere.

public static var isConfigured: Bool
public static func configure(apiKey: String, appUserID: String? = nil, baseURL: URL, logLevel: HorseLogLevel = .warn, restorePolicy: RestorePolicy = .onRestore) -> Horse

Configure once at launch, on the main thread (app delegate / App init — where you'd call Purchases.configure). Loads the cache immediately, then refreshes from the server and syncs the device's StoreKit transactions in the background.

public static func configure(with configuration: Configuration) -> Horse
public static func setLogHandler(_ handler: (@Sendable (HorseLogLevel, String) -> Void)?)
public var isAnonymous: Bool
public var appAccountToken: UUID?
public var latestCustomerInfo: CustomerInfo?

Last known customer info (cache), readable from any thread.

public var remoteConfig: RemoteConfig

Remote config for this user (cached; refreshed at launch, on foreground, after logIn). Read from any thread: Horse.shared.remoteConfig.string("paywall_headline").

public var customerInfoStream: AsyncStream<CustomerInfo>

Stream of customer info updates (fires with the current value first).

public enum FetchPolicy: Sendable
public func customerInfo(fetchPolicy: FetchPolicy = .cachedOrFetched) async throws -> CustomerInfo

Customer info according to the policy. .cachedOrFetched returns the cache when it is younger than 5 minutes; .fetchCurrent always asks the server (falls back to cache + local StoreKit state on failure).

public func isEntitled(_ identifier: String) -> Bool

Non-blocking convenience for gating UI: last known state (cache), locally re-checked. Safe to call from any thread.

public func logIn(_ newAppUserID: String) async throws -> (customerInfo: CustomerInfo, created: Bool)

Identify the user. Anonymous purchases are merged into the new id (server-side alias).

public func logOut() async throws -> CustomerInfo

Back to a fresh anonymous id. Purchases stay with the identified user on the server; StoreKit still knows this device's purchases, so restorePurchases() brings them back.

public func redeem(code: String, token: String? = nil) async throws -> (customerInfo: CustomerInfo, redemption: CodeRedemption)

Redeem an access code made in the Horse Revenue dashboard: its entitlement for a while (or for life), no purchase. With the token an earlier redemption returned, it instead moves that access to this install (a new phone, a reinstall) without using the code again, which is why the token is worth keeping somewhere a new install finds it.

Throws RedeemCodeError when the code can't be redeemed (.discountCode when it is an offering's promo code rather than an access code), HorseError.network when offline.

public func offerings() async throws -> Offerings

Offerings with StoreKit products resolved. Cached for 5 minutes.

public func invalidateOfferingsCache()
public func products(_ identifiers: [String]) async throws -> [Product]

Load arbitrary StoreKit products by id (for paywalls not driven by offerings).

public func purchase(package: Package) async throws -> PurchaseResult

Purchase a package from an offering. The purchase is credited to that offering's paywall (with the placement paywallShown gave it, if it is the presented paywall).

public func purchase(product: Product, options: Set<Product.PurchaseOption> = []) async throws -> PurchaseResult

Purchase a StoreKit product. Attaches the customer's appAccountToken so Apple's server notifications name this customer, syncs the signed transaction, then finishes it. Credited to the presented paywall when paywallShown reported one in the last 30 minutes. On visionOS the purchase is confirmed in the scene of the app's key window.

public func syncPurchases() async throws -> CustomerInfo

Claim every purchase this Apple ID owns for the current app user id, silently — RevenueCat's syncPurchases. Reads StoreKit's own records and never contacts the App Store, so it is safe at launch or right after a login; under .onRestore it is how an app claims pre-existing purchases without a Restore tap. Same as syncPurchases(isRestore: true).

It only sees what StoreKit already has on this device. A purchase StoreKit doesn't know about yet needs restorePurchases(), from a Restore button.

public func restorePurchases() async throws -> CustomerInfo

Restore Purchases — only in response to the user tapping Restore. Asks the App Store to sync first (AppStore.sync()), which can show the Apple ID sign-in or password prompt, then claims everything the Apple ID owns as syncPurchases() does. The only HorseKit call that contacts the App Store.

public func syncPurchases(isRestore: Bool) async throws -> CustomerInfo

Push the device's current StoreKit state to the server (no App Store prompt). isRestore: true also has the server refresh each subscription's status from Apple straight away rather than on its usual schedule — what a claim wants.

public func track(_ name: String, _ properties: [String: Any]? = nil)

Record something the app did: Horse.shared.track("export_started", ["stems": 4]).

Names are snake_case, up to 48 characters, and may not start with $ (those belong to the SDK). Properties take strings, numbers and booleans — at most 20, strings cut to 200 characters. Nothing throws, nothing waits for the network: events go out in batches, and survive being offline, backgrounded or killed.

Keep names and property keys to a fixed vocabulary. An id in a name (user_8f3a1c) is the one mistake that makes an events table useless: the server stops accepting new names past 200 per app, and says so in the dashboard.

public func screen(_ name: String)

Record that a screen appeared. SwiftUI: .horseScreen("Paywall") on the view instead. Repeating the current screen is ignored, so calling it from onAppear is safe.

public func flushEvents() async

Send whatever analytics events are waiting, now. The SDK already does this every 10 seconds, when the app backgrounds and when the customer changes; this is for tests and for an app that is about to do something drastic.

public func fetchRemoteConfig(force: Bool = false) async -> RemoteConfig

Fetch this user's remote config from the server (throttled to once per 5 minutes unless force). Returns the cached config on failure — the app never blocks on this.

public func joinExperiment(_ experimentID: String, variant variantID: String) async -> Bool

Puts this install on a side of a running experiment, from a link: a tester opening <app>://…?experiment=onboarding_tour&variant=tour to see the variant on their own phone, or an ad that opens the app. The side sticks like a drawn one, and the new values are here as soon as this returns (remoteConfigDidChangeNotification too). The person is left out of the test's results, since they chose their side. False when the server refused it (no such running experiment or variant) or couldn't be reached; nothing changes then.

public func setAttributes(_ attributes: [String: String?]) async
public func setEmail(_ email: String?) async
public func setDisplayName(_ name: String?) async
public func setPushToken(_ token: String?) async
public func sendAppleSearchAdsToken(_ token: @escaping @Sendable () throws -> String) async

Sends this install's AdServices attribution token, unless the server already has Apple's answer for it. HorseKit's collectAppleSearchAdsAttribution() supplies the token, so HorseKit never links AdServices. token runs off the main actor: AAAttribution.attributionToken() makes a network call of its own.

public func paywallShown(offering: String, placement: String? = nil)

Tell Horse a paywall is on screen — call it where the paywall appears (SwiftUI .onAppear, UIKit viewDidAppear), with the offering it shows and, if you like, where in the app it was opened ("onboarding", "settings", …). The dashboard divides each paywall's purchases by the times it was seen.

It also becomes the presented paywall: purchase(package:) from the same offering carries its placement, and purchase(product:) in the next 30 minutes is credited to it.

Never throws and never waits for the network: events go out together a moment later. Ids are letters, digits, _, . and -, at most 64 characters; anything else is logged and not counted (a bad placement only drops the placement).

public func paywallShown(offering: Offering, placement: String? = nil)

paywallShown(offering:placement:) with the offering the paywall shows.

public func paywallClosed(offering: String, placement: String? = nil)

Tell Horse the paywall went away — closed, swiped down, or after a purchase. Ends the presented paywall if it is this offering.

public func paywallPlanSelected(offering: String, productId: String? = nil, placement: String? = nil)

Tell Horse which plan the user picked on the paywall, before they buy — the funnel step between seeing a paywall and starting a purchase, and usually the one that explains a bad conversion. productId is optional and goes in as a property.

public func paywallPlanSelected(package: Package, placement: String? = nil)

paywallPlanSelected(offering:productId:placement:) for a package.

public func paywallClosed(offering: Offering, placement: String? = nil)

paywallClosed(offering:placement:) with the offering the paywall showed.

public func eligibleWinBackOffers(for products: [Product]) async -> [String: PaywallWinBackOffer]

The win-back offer this Apple ID can redeem now on each of products, by product id: Apple's best for them where a product has several. Products without one, a customer who isn't eligible, and any OS before iOS 18 / macOS 15 / tvOS 18 / watchOS 11 / visionOS 2 get nothing, so a paywall built on this reads and sells exactly as before for them.

Reads StoreKit's own records (Product.SubscriptionInfo.status(for:)), one request per subscription group; never throws — a StoreKit failure is logged and means none.

public func eligibleWinBackOffer(for package: Package) async -> PaywallWinBackOffer?

eligibleWinBackOffers(for:) for one package's product.

public func purchase(package: Package, winBackOffer: PaywallWinBackOffer) async throws -> PurchaseResult

Buys package with a win-back offer (one eligibleWinBackOffer(for:) returned): the customer's appAccountToken is attached and the purchase is credited to the offering's paywall, as purchase(package:) does.

Throws HorseError.storeKit when the OS has no win-back offers or the product has no offer with that id — rather than buying at a price the customer wasn't shown. StoreKit itself refuses the purchase if the Apple ID is no longer eligible.

public func paywall(for offering: Offering, draft: Bool = false) async throws -> Paywall

The paywall designed for offering in the dashboard, in the device's language.

Served from the disk cache when it is the version offerings() reported and the device still prefers the same languages, so a paywall opens without waiting for the network. A stale copy is better than none: offline, the last one fetched is returned. draft: true fetches the unpublished draft for a debug build — never cached.

Throws PaywallError.notFound when the offering has no published design: show the app's own paywall then.

public func paywall(forOfferingIdentifier identifier: String, draft: Bool = false) async throws -> Paywall

paywall(for:) by offering id. Without the version offerings() knows, it always asks.

#PeriodType

What the customer pays right now: the list price (normal), an introductory free trial, a paid introductory price, or promo — a promotional offer, an offer code or a win-back offer.

public enum PeriodType: String, Codable, Sendable
case trial, intro, normal, promo

#OwnershipType

public enum OwnershipType: String, Codable, Sendable

#Store

Where a purchase was made. A customer of an app on both stores can hold either, and the iPhone sees what was bought on Android too (the same entitlements).

public enum Store: String, Codable, Sendable
case appStore = "app_store", playStore = "play_store", promotional

#SubscriptionStatus

paused is Google Play's: the subscriber put it on hold, and it grants nothing until it resumes.

public enum SubscriptionStatus: String, Codable, Sendable
case active, expired, billingRetry = "billing_retry", gracePeriod = "grace_period", revoked, paused

#EntitlementInfo

public struct EntitlementInfo: Codable, Sendable, Equatable
public let identifier: String
public let isActive: Bool
public let willRenew: Bool
public let periodType: PeriodType
public let latestPurchaseDate: Date
public let originalPurchaseDate: Date
public let expirationDate: Date?
public let store: Store
public let productIdentifier: String
public let isSandbox: Bool
public let unsubscribeDetectedAt: Date?
public let billingIssueDetectedAt: Date?
public let ownershipType: OwnershipType
public init(identifier: String, isActive: Bool, willRenew: Bool, periodType: PeriodType, latestPurchaseDate: Date, originalPurchaseDate: Date, expirationDate: Date?, store: Store, productIdentifier: String, isSandbox: Bool, unsubscribeDetectedAt: Date? = nil, billingIssueDetectedAt: Date? = nil, ownershipType: OwnershipType = .purchased)

#EntitlementInfos

public struct EntitlementInfos: Codable, Sendable, Equatable
public let all: [String: EntitlementInfo]
public let active: [String: EntitlementInfo]
public subscript(_ id: String) -> EntitlementInfo?
public init(all: [String: EntitlementInfo], active: [String: EntitlementInfo])

#SubscriptionInfo

public struct SubscriptionInfo: Codable, Sendable, Equatable
public struct Price: Codable, Sendable, Equatable
public let productIdentifier: String
public let originalTransactionId: String
public let status: SubscriptionStatus
public let isActive: Bool
public let willRenew: Bool
public let periodType: PeriodType
public let purchaseDate: Date
public let originalPurchaseDate: Date
public let expiresDate: Date?
public let gracePeriodExpiresDate: Date?
public let unsubscribeDetectedAt: Date?
public let billingIssuesDetectedAt: Date?
public let refundedAt: Date?
public let isSandbox: Bool
public let ownershipType: OwnershipType
public let storefront: String?
public let price: Price?
public var store: Store

Where it was bought.

#NonSubscriptionTransaction

public struct NonSubscriptionTransaction: Codable, Sendable, Equatable
public let transactionIdentifier: String
public let productIdentifier: String
public let purchaseDate: Date
public let isSandbox: Bool
public let revokedAt: Date?

#CustomerInfo

public struct CustomerInfo: Codable, Sendable, Equatable
public let originalAppUserId: String
public let requestDate: Date
public let firstSeen: Date
public let entitlements: EntitlementInfos
public let activeSubscriptions: Set<String>
public let allPurchasedProductIdentifiers: Set<String>
public let latestExpirationDate: Date?
public let subscriptions: [String: SubscriptionInfo]
public let nonSubscriptions: [NonSubscriptionTransaction]
public let managementURL: URL?
public let appAccountToken: String
public let blockedEntitlements: [String]

Entitlements an admin is blocking for this customer (support/testing). "*" = all. The purchase is still on file; it just doesn't grant while the block is in place — so the SDK must not re-grant it from StoreKit either.

public var isFromServer: Bool

False when this info was assembled on-device from StoreKit (server unreachable).

public func isEntitled(_ identifier: String) -> Bool

Convenience: is this entitlement active right now (also re-checks expiration locally).

#PackageType

public enum PackageType: String, Codable, Sendable
case lifetime, annual, sixMonth = "six_month", threeMonth = "three_month", twoMonth = "two_month", monthly, weekly, custom

#Package

public struct Package: Identifiable, Sendable
public let identifier: String
public let packageType: PackageType
public let storeProduct: Product
public let offeringIdentifier: String
public var id: String
public var localizedPriceString: String

Convenience mirrors of RevenueCat's package helpers.

public var productIdentifier: String

#Offering

public struct Offering: Identifiable, Sendable
public let identifier: String
public let serverDescription: String
public let metadata: [String: JSONValue]
public let availablePackages: [Package]
public let paywallVersion: Int?

The version of the paywall designed for this offering in the dashboard (PaywallView); nil when it has none, or when the server is too old to say.

public var id: String
public var hasPaywall: Bool

The dashboard has a published paywall design for this offering.

public init(identifier: String, serverDescription: String, metadata: [String: JSONValue], availablePackages: [Package], paywallVersion: Int? = nil)
public var lifetime: Package?
public var annual: Package?
public var sixMonth: Package?
public var threeMonth: Package?
public var twoMonth: Package?
public var monthly: Package?
public var weekly: Package?
public func package(identifier: String) -> Package?
public func package(forProduct productId: String) -> Package?
public func getMetadataValue<T>(for key: String, default defaultValue: T) -> T
public func string(_ key: String, default d: String = "") -> String
public func bool(_ key: String, default d: Bool = false) -> Bool
public func number(_ key: String, default d: Double = 0) -> Double
public func int(_ key: String, default d: Int = 0) -> Int
public func json(_ key: String) -> Any?

Nested objects/arrays as Foundation types.

public func decode<T: Decodable>(_ key: String, as type: T.Type) -> T?

Decode a nested object into your own Decodable (e.g. a paywall layout struct).

public func decodeMetadata<T: Decodable>(as type: T.Type) -> T?

The whole metadata dictionary decoded into your own type.

public func hasMetadata(_ key: String) -> Bool

#Offerings

public struct Offerings: Sendable
public let all: [String: Offering]
public let current: Offering?
public let placements: [String: String]
public func offering(identifier: String) -> Offering?
public subscript(_ identifier: String) -> Offering?
public func currentOffering(forPlacement placement: String) -> Offering?

Offering for a placement (e.g. "onboarding"), falling back to current.

#PurchaseResult

public struct PurchaseResult: Sendable
public let customerInfo: CustomerInfo
public let transaction: Transaction?
public let userCancelled: Bool
public let syncedWithServer: Bool

False if the server could not be reached; the transaction is queued and will be synced.

#HorseError

public enum HorseError: Error, LocalizedError, Sendable
case notConfigured
case network(underlying: String)
case server(status: Int, code: String, message: String)
case invalidResponse
case productNotFound(String)
case purchaseCancelled
case purchasePending
case storeKit(underlying: String)
case verificationFailed
public var errorDescription: String?
public var isCancellation: Bool

#CodeRedemption

Access given by redeeming an access code (Horse.redeem(code:token:)): an entitlement for a while, or for life, with no purchase. CustomerInfo shows it like any other entitlement, with store == .promotional.

public struct CodeRedemption: Codable, Sendable, Equatable
public let code: String

The code as it was handed out, e.g. "7KQ4-XM9P-R2DW".

public let entitlementId: String
public let expirationDate: Date?

When the access ends; nil = for life.

public let redeemedAt: Date
public let token: String

This person's claim on the access. Keep it where a new install of the app finds it (iCloud's key-value store): redeem(code:token:) with it moves the access to that install without using the code again.

public let isNew: Bool

A new use of the code (false: this person's existing access, claimed again).

public let moved: Bool

The access came over from another install.

#RedeemCodeError

Why a code couldn't be redeemed.

public enum RedeemCodeError: Error, LocalizedError, Sendable, Equatable
case invalid

No such code.

case disabled

Switched off, or the access it gave was taken away.

case expired

Past its last day, or the access it gave has ended.

case usedUp

Everyone it was for has redeemed it.

case discountCode(offeringId: String)

Not an access code but a discount code: the promo code of this offering.

case rateLimited

Too many attempts from this device; try again in a minute.

public var errorDescription: String?

#JSONValue

public enum JSONValue: Codable, Sendable, Equatable
case string(String), number(Double), bool(Bool), null, array([JSONValue]), object([String: JSONValue])
public var anyValue: Any
public var stringValue: String?
public var boolValue: Bool?
public var doubleValue: Double?

#RemoteConfig

Values from the Horse Revenue dashboard (Remote config tab), already evaluated for this user: rules by app version / country / subscription state applied, and experiment variants assigned. Read like Firebase Remote Config; refreshed by the SDK, cached offline.

public struct RemoteConfig: Codable, Sendable, Equatable
public let values: [String: JSONValue]

key → value (String / Double / Bool / JSON as [String: Any] or [Any]).

public let experiments: [String: String]

experimentId → variantId for experiments this user is currently in.

public let fetchedAt: Date
public static let empty
public init(values: [String: JSONValue], experiments: [String: String], fetchedAt: Date)
public func string(_ key: String, default d: String = "") -> String
public func bool(_ key: String, default d: Bool = false) -> Bool
public func number(_ key: String, default d: Double = 0) -> Double
public func int(_ key: String, default d: Int = 0) -> Int
public func json(_ key: String) -> Any?

JSON values (objects/arrays) as Foundation types.

public func decode<T: Decodable>(_ key: String, as type: T.Type) -> T?
public func has(_ key: String) -> Bool
public func variant(_ experimentId: String) -> String?

Variant id if this user is in the experiment (nil = not in it / not running).

public func isIn(_ experimentId: String, variant: String) -> Bool

#View (extension)

public func horseScreen(_ name: String) -> some View

Report this view as a screen while it is on screen: one line per screen, which is as automatic as SwiftUI gets.

PaywallView().horseScreen("Paywall")

Reporting the same screen twice in a row does nothing, so putting it on a view that reappears is safe.

#PaywallDesign (extension)

public var assetURLs: [URL]

Every image and video the design shows, for prefetching.

#PaywallAssetCache

Downloaded paywall images and videos, on disk by URL, so a paywall opens fully drawn and a video plays from a file instead of buffering. File URLs (previews, bundled art) are used as they are.

public actor PaywallAssetCache
public static let shared
public func cachedFile(for url: URL) -> URL?

Where url is on disk, if it already is (no waiting).

public func file(_ url: URL) async -> URL?

url on disk, downloading it first if need be; nil when it can't be had.

public func prefetch(_ urls: [URL]) async

#PaywallMemory

Closes counted for nextPaywall and when a banner's countdown started, per install.

public struct PaywallMemory
public init(defaults: UserDefaults = .standard, namespace: String)
public static var current: PaywallMemory

The configured SDK's memory, or one of its own for previews.

public func closes(_ offeringId: String) -> Int
public func recordClose(_ offeringId: String, next: PaywallDesign.Behavior.NextPaywall?) -> Bool

Counts a close of offeringId's paywall; true when this one should open the next paywall instead of dismissing.

public static func afterClose(count: Int, next: PaywallDesign.Behavior.NextPaywall?) -> (count: Int, openNext: Bool)

The Nth close opens the next paywall and starts the count again, so it comes back every N closes rather than on every close after the Nth.

public func timerStart(offeringId: String, blockId: String, now: Date = Date()) -> Date

When this install first saw the banner's countdown (now, if this is the first time).

#PaywallLog

The SDK's log, for HorseKitUI (Horse.setLogHandler sees these lines too).

public enum PaywallLog
public static func warn(_ message: String)

#HorseLogLevel

public enum HorseLogLevel: Int, Comparable, Sendable
case debug = 0, info, warn, error, off
public static func < (a: HorseLogLevel, b: HorseLogLevel) -> Bool

#HorseKitUI

Paywalls designed in the dashboard, drawn natively in SwiftUI. import HorseKitUI

#PaywallView

The paywall designed for an offering in the Horse Revenue dashboard, drawn natively.

.fullScreenCover(isPresented: $showPaywall) {
    PaywallView(placement: "onboarding")
        .onPurchaseCompleted { _ in unlock() }
        .paywallComponent("mascot") { _ in MascotView() }
}

It loads the offering and its design (instantly from the cache when it has been seen), checks the user's intro-offer eligibility before saying "free trial" — and, when the design sells win-back offers, which one this Apple ID can redeem (iOS 18) — buys through Horse.shared.purchase(package:) (with the win-back offer when the plan shows one), and reports shown / plan selected / closed with no app code. With no design for the offering — or offline with nothing cached — it shows fallback: the app's own paywall, ideally.

public struct PaywallView: View
public init(draft: Bool = false)

The current offering's paywall (offerings().current).

public init(placement: String, draft: Bool = false)

The paywall of the offering a placement names (falling back to the current one). Blocks the dashboard limited to some placements show only when it is one of them.

public init(offering: Offering, placement: String? = nil, draft: Bool = false)

The paywall of this offering, opened from placement if you say where.

public init(offeringIdentifier: String, placement: String? = nil, draft: Bool = false)

The paywall of the offering with this id. An empty id is the placement's offering (or the current one), so an app can hand its own "which offering" setting straight through.

public init<Fallback: View>(offeringIdentifier: String, placement: String? = nil, draft: Bool = false, @ViewBuilder fallback: () -> Fallback)

The same, with the view to show when there is no design to draw (the app's own paywall).

public init<Fallback: View>(placement: String, draft: Bool = false, @ViewBuilder fallback: () -> Fallback)

The same, with the view to show when there is no design to draw (none published, or offline and never seen).

public init<Fallback: View>(offering: Offering? = nil, placement: String? = nil, draft: Bool = false, @ViewBuilder fallback: () -> Fallback)
public init(design: PaywallDesign, packages: [PaywallPackage], offeringIdentifier: String = "preview", locale: String = "en", placement: String? = nil)

Draws design with packages and buys nothing — for SwiftUI previews, design reviews and tests. design is the SDK's (or the dashboard's) JSON decoded as PaywallDesign. A package's product can carry an intro offer and a win-back offer (PaywallProductInfo.winBack, isEligibleForWinBack) to preview what an eligible customer sees; a win-back shows only when the design sells them (behavior.winBackOffers), as on a device.

public var body: some View

#View (extension)

public func presentPaywall(isPresented: Binding<Bool>, placement: String? = nil) -> some View

Presents the paywall for placement (the current offering's without one) while isPresented is true: full screen on iPhone and iPad, a sheet elsewhere.

public func presentPaywallIfNeeded(requiredEntitlement: String, placement: String? = nil) -> some View

Presents the paywall whenever the user lacks requiredEntitlement, and takes it away once they have it (a purchase, a restore, a code). Waits for Horse to know who the user is, so a subscriber never sees it flash past at launch.

public func paywallComponent<V: View>(_ component: String, @ViewBuilder _ view: @escaping @MainActor ([String: JSONValue]) -> V) -> some View

The view for the custom blocks (and custom backgrounds) named component in the dashboard — a mascot, a special animation, anything the app draws itself. It gets the props the dashboard set on the block. A component nobody registered leaves its space empty.

PaywallView(placement: "onboarding")
    .paywallComponent("mascot") { props in MascotView(mood: props["mood"]?.stringValue ?? "happy") }
public func paywallColors(_ colors: [String: Color]) -> some View

Replaces the design's theme colours by name — background, text, secondaryText, accent, onAccent, surface, border, selected, badge, onBadge — for an app whose look follows a setting of its own (a theme the person picked). Names left out keep the design's colour, and a design colour that names another ("selected": "accent") follows the app's colour for that one.

PaywallView(placement: "settings")
    .paywallColors(["background": palette.background, "accent": palette.accentDeep])
public func paywallFollowsDeviceAppearance(_ follows: Bool = true) -> some View

Draws the paywall in the device's light or dark instead of the design's theme.appearance, for an app whose paywallColors change with it: the paywall then matches the screens around it. Without it a design made light stays light on a phone in dark mode, and turns whatever shares its screen (an onboarding it slides in from) light too.

public func onPlanSelected(_ action: @escaping @MainActor (String) -> Void) -> some View

The person picked a plan (not the one selected when the paywall opened) — the package id. For the app's own touch: a sound, an animation.

public func onPurchaseCompleted(_ action: @escaping @MainActor (CustomerInfo) -> Void) -> some View

After a purchase made on the paywall went through.

public func onPurchaseCompleted(_ action: @escaping @MainActor (PaywallPurchase) -> Void) -> some View

After a purchase made on the paywall went through, with what was bought: the package, the product as shown (did a trial start?), the placement. Both onPurchaseCompleteds may be set; both are called. Name the type in the closure to pick this one:

.onPurchaseCompleted { (purchase: PaywallPurchase) in
    ads.purchased(plan: purchase.packageId, startsTrial: purchase.startedFreeTrial)
}
public func onRestoreCompleted(_ action: @escaping @MainActor (CustomerInfo) -> Void) -> some View

After Restore found something to restore.

public func onPurchaseFailed(_ action: @escaping @MainActor (Error) -> Void) -> some View

A purchase or restore failed (the user cancelling is not a failure). The paywall has already told the user.

public func onPaywallDismiss(_ action: @escaping @MainActor () -> Void) -> some View

The paywall wants to go away: closed, or done after a purchase. Inside a sheet or a cover it dismisses itself as well; embedded anywhere else, this is how the app hears of it.

#PaywallPurchase

A purchase made on a paywall, as the app hears of it: what was bought and from where, for the app's own reports (an ad network wants the plan and whether a trial started).

public struct PaywallPurchase: Sendable
public let customerInfo: CustomerInfo
public let packageId: String

The offering's package that was bought.

public let product: PaywallProductInfo

The product as the paywall showed it when it was bought — its intro offer, and whether this person could still take it.

public let placement: String?

Where in the app the paywall was opened, if it was said.

public init(customerInfo: CustomerInfo, packageId: String, product: PaywallProductInfo, placement: String?)
public var startedFreeTrial: Bool

The purchase started a free trial: the plan has one and this person could still take it.

public var startedIntroOffer: Bool

The purchase started a paid introductory price (pay as you go, or up front).

public var startedWinBackOffer: Bool

The purchase used a win-back offer (product.winBack): someone who had left came back.

#EnvironmentValues (extension)

public var paywallIsSplit: Bool

True in the background of a paywall split on a wide screen (layout.wide: split), where it fills one half beside the page. An app's own background view can read it to fill its half instead of showing itself whole.

#PaywallPackage

One plan a paywall can sell: the offering's package id and what the words need to know about its product. Built from a real Package by PaywallView; made by hand for previews.

public struct PaywallPackage: Identifiable, Sendable
public let id: String
public var product: PaywallProductInfo
public init(id: String, product: PaywallProductInfo)

#HorseKitSearchAds

Apple Search Ads attribution. Links AdServices only. import HorseKitSearchAds

#Horse (extension)

public func collectAppleSearchAdsAttribution() async

Apple Search Ads attribution, like Qonversion's collectAppleSearchAdsAttribution() and RevenueCat's enableAdServicesAttributionTokenCollection(): sends this install's AdServices token, which the server trades with Apple for the campaign, ad group and keyword the install came from (or "not from Search Ads"). The dashboard's Search Ads tab and the customer page show it; the customer also gets $mediaSource, $campaign, $adGroup, $keyword, $ad.

Call it at every launch: it sends once per install and returns at once after that. It needs no App Tracking Transparency prompt (Apple adds the click date when tracking is allowed). The simulator has no token; TestFlight and Xcode builds get Apple's sample answer, which the server keeps apart from real installs.

#HorseKitAttribution

For apps that run ads: device identifiers and ad-network ids. Re-exports HorseKit and HorseKitSearchAds. import HorseKitAttribution

#Horse (extension)

Attribution attributes — the RevenueCat-named keys the server's ad integrations read (Meta Ads today). Each helper is a thin wrapper over setAttributes; nil clears the attribute.

// After the App Tracking Transparency prompt (and again whenever it may have changed):
await Horse.shared.collectDeviceIdentifiers()
await Horse.shared.setFBAnonymousID(AppEvents.shared.anonymousID)   // Meta SDK

The IP address and User-Agent are recorded by the server from the SDK's own requests.

public func collectDeviceIdentifiers() async

Sets $idfv, $attConsentStatus (notDetermined / restricted / denied / authorized) and — only when tracking is authorised and the value is real — $idfa. Never shows the ATT prompt itself; call it after your prompt resolves.

public func setFBAnonymousID(_ id: String?) async

Meta: AppEvents.shared.anonymousID from the Facebook SDK → $fbAnonId.

public func setAppsflyerID(_ id: String?) async

AppsFlyer: AppsFlyerLib.shared().getAppsFlyerUID() → $appsflyerId.

public func setFirebaseAppInstanceID(_ id: String?) async

Firebase: Analytics.appInstanceID() → $firebaseAppInstanceId.

public func setMixpanelDistinctID(_ id: String?) async

Mixpanel: Mixpanel.mainInstance().distinctId → $mixpanelDistinctId.

public func setPhoneNumber(_ phoneNumber: String?) async
public func setMediaSource(_ mediaSource: String?) async
public func setCampaign(_ campaign: String?) async
public func setAdGroup(_ adGroup: String?) async
public func setAd(_ ad: String?) async
public func setKeyword(_ keyword: String?) async
public func setCreative(_ creative: String?) async