Display a paywall

Present the paywall assigned to a location and react to how it ended.

presentFlow(location:) presents the paywall or onboarding flow assigned to a paywall location in Studio, and returns how it ended. A location is the spot in your app where a flow is shown; the location argument takes its slug, such as onboarding. Paywalls and onboarding flows are explained in Paywalls in your app.

Add the paywall renderer

Paywalls are drawn natively, with UIKit's own views, by the VoidhashUI library of the Swift package. Add VoidhashUI to your app target next to Voidhash; the SDK finds the renderer once your app links it, with no option to set. In a Package.swift, add .product(name: "VoidhashUI", package: "voidhash") to the target's dependencies.

VoidhashUI is in the package from the first release that includes its prebuilt core. Its core runs on devices and in the Simulator on Apple silicon Macs, not in the Simulator on Intel Macs. Without VoidhashUI, presentFlow throws FlowError.rendererMissing and the SDK makes no paywall requests.

Present a paywall

The call returns once the paywall or flow has ended and left the screen, so you can present your next screen as soon as it returns.

do {
    let result = try await voidhash.presentFlow(location: "onboarding")
    switch result.outcome {
    case FlowResult.purchased:
        print("Bought \(result.productId ?? "")")
    case FlowResult.restored:
        print("Restored")
    case FlowResult.dismissed:
        break
    default:
        handleOnboarding(result.outcome, result.output)
    }
} catch let error as FlowError {
    showOwnUpgradeScreen(reason: error)
}

Every ending returns a FlowResult with the same three properties:

PropertyValue
outcomeHow the flow ended, as a string. See the table below.
outputThe flow's outputs by name, whichever way it ended. Empty when it declares none.
productIdThe slug of the product bought, when the outcome is purchased. Otherwise nil.
OutcomeMeaning
FlowResult.purchasedA purchase on a paywall completed, and the paywall closed.
FlowResult.restoredA restore on a paywall completed, and the paywall closed.
FlowResult.dismissedThe user closed it, your app called dismissFlow() or cancelled the task awaiting presentFlow, or another presentFlow replaced it.
Any other stringThe flow ran a Finish flow action. The outcome is the one that action names, such as completed or skipped.

A flow that couldn't be shown isn't an outcome. presentFlow throws a FlowError then, and also when a paywall on screen can no longer be drawn. See When nothing is shown.

An onboarding flow doesn't end on a purchase or restore: it continues to its next screen and ends with its own outcome or dismissed. It never ends as purchased or restored. Check access after any result instead of relying on it; see Check access.

A cancelled or failed purchase leaves the paywall on screen so the user can try again. Purchases run through purchase(_:options:), with the offer the paywall names or the introductory offer the user can have, so the SDK syncs and finishes them as usual. In observer mode they're refused with READ_ONLY_PURCHASE_NOT_ALLOWED, reported through onWarning.

A paywall can intercept the user's first attempt to close it, for example to show a last offer. The paywall then stays on screen and presentFlow keeps waiting; the next attempt closes it. dismissFlow() always closes it at once.

Present from a view controller

The paywall is presented full screen from the key window's top view controller. UIKit apps can choose the presenter:

let result = try await voidhash.presentFlow(location: "onboarding", from: viewController)

The view controller has to be on screen and not presenting anything itself. Otherwise presentFlow throws FlowError.presentationFailed.

Close the paywall from your own code with await voidhash.dismissFlow(); the pending presentFlow returns the outcome dismissed. dismissFlow() returns once the paywall is off the screen. Called while the paywall is still loading, it keeps it from being shown. Cancelling the task that awaits presentFlow does the same.

Shutting the client down, or configuring the SDK again, also ends its paywalls: one on screen is closed and returns the outcome dismissed, and one that is still loading isn't shown and throws FlowError.disabled.

Exchange data with a flow

A location can declare what your app and the flow shown there exchange: inputs your app passes, outputs it reads back, the outcomes a flow can end with, and app actions a flow can call. Values are strings, numbers, booleans or lists of strings. In Swift they are FlowValues, which string, number, boolean and string array literals convert to: ["interests": ["yoga", "chess"]]. A list holds each string once, at most 100 of at most 200 characters; a flow ignores a longer one.

Pass inputs

Pass values by name when you present. An input you don't pass keeps the default it was declared with.

let result = try await voidhash.presentFlow(
    location: "onboarding",
    input: ["firstName": "Ada", "credits": 3, "isMember": true]
)

Change inputs while the flow is on screen with updateFlowInput. Inputs you don't name keep their values, and the call does nothing when no flow is shown.

await voidhash.updateFlowInput(["credits": 5])

Read outputs

result.output holds the flow's outputs by name, whichever way the flow ended, including a purchase or the user closing it. Read a value with stringValue, numberValue or boolValue, and fall back to your own default: a flow built before an output was added doesn't report it.

let goal = result.output["goal"]?.stringValue ?? "none"
let reminders = result.output["reminders"]?.boolValue ?? false

Handle app actions

A flow can call a function of your app, for example to open your own picker, and use the reply. Pass a handler for each action by name. It receives the call's arguments and returns the reply.

let result = try await voidhash.presentFlow(
    location: "onboarding",
    actions: [
        "pickGoal": { arguments in
            let current = arguments["current"]?.stringValue ?? ""
            let goal = try await goalPicker.pick(startingFrom: current)
            return ["goal": .string(goal)]
        }
    ]
)

When a handler throws, or the flow calls an action you passed no handler for, the call fails inside the flow, and the flow carries on with what its designer chose for that case. The paywall stays on screen. In a debug build, a call without a handler is also reported through onWarning, naming the action and the location. A handler still running when the flow ends is cancelled.

Tell Voidhash which revision your app supports

Every saved change to what a location exchanges makes a new revision of it. Name the revision your app was built against, and Voidhash only shows that app flows it can run: a flow calling an action your app version doesn't handle yet isn't shown to it.

// For one presentation:
try await voidhash.presentFlow(location: "onboarding", revision: 3)

// Or once, for presenting and preloading:
options.flowRevisions = ["onboarding": 3]

An app that names no revision counts as revision 0. It is shown flows that call no app action and end only as completed, purchased, restored or dismissed.

Typed locations

The Voidhash CLI can generate Swift types for a location, so you don't write names and conversions by hand. The generated code declares the location's input, output, outcome and action types and a FlowLocation that carries the slug and the revision. Present it with the typed call:

let result = try await voidhash.presentFlow(
    OnboardingFlow.location,
    input: OnboardingFlow.Input(firstName: "Ada", credits: 3),
    actions: OnboardingFlow.Actions(pickGoal: { current in
        try await goalPicker.pick(startingFrom: current)
    })
)

if result.outcome == .completed {
    save(result.output.goal)
}

The typed call returns a TypedFlowResult whose outcome and output are the generated types, and it throws FlowError like the untyped call.

Choose what paywalls may do

Purchases, restores, closing, navigation and analytics always work. Anything else a paywall can do is off until you grant it in flowCapabilities. By default only .links is granted.

options.flowCapabilities = [.links, .notifications, .attributes]
CapabilityLets the paywall
.linksOpen URLs outside the app (Open URL).
.notificationsAsk for notification permission (Request permission).
.trackingAsk for App Tracking Transparency permission (Request permission), through a handler you register (below).
.attributesSave values as person attributes (Set user attribute), like setPersonAttributes.

An action you didn't grant is skipped and reported through onWarning. A Request permission step for a permission you didn't grant goes on at its Unavailable exit.

The SDK asks for notifications itself, with the alert, badge and sound options. It has no tracking prompt of its own and neither links nor references AppTrackingTransparency, so apps that never ask for tracking don't carry it. To let a flow ask, add the framework and NSUserTrackingUsageDescription to your app and register a handler; without one, the flow hears that tracking is unavailable. Ask only once the app is active: asked earlier, the system shows no prompt and answers not determined.

import AppTrackingTransparency
import UIKit
import Voidhash

options.flowCapabilities = [.links, .tracking]
options.flowPermissionHandlers = [
    FlowCapability.tracking.rawValue: FlowPermissionHandler(
        status: {
            switch ATTrackingManager.trackingAuthorizationStatus {
            case .authorized: return .granted
            case .denied, .restricted: return .denied
            case .notDetermined: return .notDetermined
            @unknown default: return .unavailable
            }
        },
        request: {
            let active = await MainActor.run { UIApplication.shared.applicationState == .active }
            if !active {
                let becameActive = NotificationCenter.default.notifications(
                    named: UIApplication.didBecomeActiveNotification)
                for await _ in becameActive { break }
            }
            switch await ATTrackingManager.requestTrackingAuthorization() {
            case .authorized: return .granted
            case .denied, .restricted: return .denied
            default: return .unavailable
            }
        }
    )
]

To ask for notifications in your own way, for example after a screen of your own or with provisional authorization, register a handler for them too. The SDK uses yours instead of its prompt:

options.flowCapabilities = [.links, .notifications]
options.flowPermissionHandlers = [
    FlowCapability.notifications.rawValue: FlowPermissionHandler(
        status: {
            switch await UNUserNotificationCenter.current().notificationSettings().authorizationStatus {
            case .authorized, .provisional, .ephemeral: return .granted
            case .denied: return .denied
            default: return .notDetermined
            }
        },
        request: {
            let center = UNUserNotificationCenter.current()
            let granted = try? await center.requestAuthorization(options: [.alert, .badge, .provisional])
            return granted == true ? .granted : .denied
        }
    )
]

The SDK calls a handler from its own tasks, off the main actor. status runs each time a flow is configured and each time the app becomes active while a flow is shown, so keep it cheap and never prompt from it. request must return once the person answered: until then that flow's request waits, and so does any other flow's request for the same permission. A flow that is dismissed stops waiting, and the next flow asks again. A permission's status stays on the device unless the flow puts it into a tracked event's property or a person attribute.

Saved progress

An onboarding flow saves its progress on the device as the user moves through it, separately for each person and flow, for up to 90 days. When the same flow is presented again, it starts with what it saved, so earlier answers are kept; the user starts again on the first screen. Inputs aren't saved: the flow always uses the ones your app passes.

A Finish flow action clears the saved progress, and so does a purchase on a paywall. A purchase inside an onboarding flow doesn't. Saved progress belongs to the current distinct ID, so after identify or signOut the flow starts fresh.

When nothing is shown

presentFlow throws a FlowError. Its description starts with a stable code.

ErrorCodeCause
.notAssignedFLOW_NOT_ASSIGNEDNothing is assigned to the location, the location doesn't exist or is archived, or none of its recent builds is one this app can show.
.unavailableFLOW_UNAVAILABLEThe device has never loaded this location and can't reach Voidhash, the paywall couldn't be downloaded, or it wasn't ready to show within 15 seconds.
.rendererMissingFLOW_RENDERER_MISSINGThe app doesn't link VoidhashUI.
.unsupportedPackage(abiVersion:)FLOW_UNSUPPORTED_PACKAGEThe location's build uses a package format this app's SDK build can't read. abiVersion names it.
.presentationFailed(String)FLOW_PRESENTATION_FAILEDThere was nothing to present from, the view controller you passed can't present, or the paywall can no longer be drawn.
.disabledFLOW_DISABLEDThe client is disabled or shut down.

FLOW_NOT_ASSIGNED is the normal answer for a location you haven't set up. Keep a fallback upgrade screen for important entry points.

Caching and offline

The SDK caches what each location shows for up to 7 days, so a location shown once works offline:

  • An answer is fresh for 5 minutes. Within them, presentFlow shows the cached paywall without asking Voidhash. After them, presenting asks Voidhash again and waits up to 500 ms for the reply; without one, it shows the cached paywall while the request finishes.
  • At launch the SDK asks again for every location it remembers. When the app returns to the foreground, and when the device gets its connection back, each at most once a minute, it asks again, in the background, for those whose answer is older than 5 minutes. Empty answers are cached the same way. So a deploy, a withdrawn build or a location you switched off reaches an online device within about 5 minutes, and a device that was offline as soon as it is back.
  • A paywall that can't be downloaded falls back to the one the location showed last, unless Voidhash withdrew that build. A withdrawn build is deleted from the device and never shown again, offline either, whichever cached answer names it; the location then shows nothing and presentFlow throws FlowError.unavailable. A build you restore is shown again once an answer serves it. A paywall you ship with the app is refused only once the device has heard of its withdrawal.

Paywalls in your app compares this with the other SDKs.

A paywall has 15 seconds from the presentFlow call to be ready to show. When it takes longer, nothing is shown, then or later, and presentFlow throws FlowError.unavailable. The download carries on, so the next presentation finds the paywall on the device. A paywall on screen has no time limit.

Download addresses

Paywalls, their images and their runtime modules download only over HTTPS from hosts on the internet. An address that names the device itself, a .local name or a private network is refused before anything connects to it, and so is a redirect to one; the paywall then fails like any other download. Your baseUrl's host is trusted in every build. Debug builds also download over http from a server on the device (localhost, 127.0.0.1, ::1) and from the host of a baseUrl you set with http, for local development.

A custom flowRenderer that downloads something a flow names, such as an image, asks FlowUrlPolicy first: download a URL only when FlowUrlPolicy.permits(url) is true, and follow a redirect only when FlowUrlPolicy.permitsRedirect(from:to:) is. The SDK's own downloads report a refused address as FlowDownloadError.refusedUrl.

import Foundation
import Voidhash

/// Whether a custom renderer may request `url`, reached by a redirect from `origin` if any.
func mayDownload(_ url: URL, redirectedFrom origin: URL?) -> Bool {
    guard let origin else { return FlowUrlPolicy.permits(url) }
    return FlowUrlPolicy.permitsRedirect(from: origin, to: url)
}

Loading screen

Apps show a loading screen while a paywall loads from the network. When a paywall has to wait for the network, the SDK shows it 0.4 seconds after the presentFlow call, at least long enough to be read, until the paywall takes its place. A paywall already on the device appears before then, without it. The loading screen has a spinner, which VoiceOver announces, and a close button, on the system background in light and dark mode.

Closing it, or the VoiceOver escape gesture, ends the presentation: presentFlow returns the outcome dismissed with wasShown set to false, which tells it apart from a paywall the end user closed (wasShown is true then). wasShown is also false when your app dismissed a paywall that was still loading. Analytics report $paywall_load_cancelled with cancelledBy: "end_user" only once Voidhash's answer named the paywall; one left while its location was still being resolved reports nothing, since there is no paywall yet to name.

To show your own view instead, or none, configure the renderer:

import VoidhashUI

var renderer = FlowViewRenderer()
renderer.loading = .custom { cancel in
    MyLoadingView(onClose: cancel)  // a UIView; call cancel to let the user leave
}
// Or keep your own screen until the paywall is ready:
// renderer.loading = .none
options.flowRenderer = renderer

Your view fills the screen, so lay it out within its safe area. The VoiceOver escape gesture leaves your view too.

Ship a paywall with the app

On a first launch without a connection, or while Voidhash can't be reached, a location the device has never loaded shows nothing. To show a paywall then, ship it in the app: add a folder named VoidhashFlows to the app target as a folder reference, and write the location's files into it with the Voidhash CLI:

voidhash location bundle onboarding --out MyApp/VoidhashFlows

It writes two files per location: onboarding.json, the location's answer, and onboarding.vhfp, the paywall's build, checked against the answer's SHA-256. The answer is what a new anonymous person is shown: never a pin or a targeting rule, for a location with an A/B test its control arm, and while the build the location shows is withdrawn, the earlier build apps are served instead. If you present the location with a revision, pass it: --revision onboarding=2.

Run the command in your release build step. The SDK stops showing the files after their notAfter, 90 days from the day the command ran, not from your release: if you release less often than that, new installs show nothing offline after the 90 days unless you pass a later --not-after or --no-expiry. More on the command.

The SDK shows the shipped paywall only when it has no answer for the location and couldn't reach Voidhash (no connection, a timeout or a server error). It never shows it:

  • when Voidhash answered, a rejected key or another error included;
  • when Voidhash answered earlier that the location shows nothing, however long ago (that answer is kept per person and SDK build);
  • after notAfter, when the file doesn't match the build's SHA-256, or when the app presents another revision of the location;
  • when the device has heard that Voidhash withdrew that build.

A withdrawal reaches a device only with an answer, so on a first launch offline the shipped build is shown however old it is, until its notAfter. Keep notAfter close and bundle again when you deploy. An old shipped paywall can offer a product you've since unlinked in Voidhash: the purchase goes through in the store but grants nothing until you link the product again.

Purchases from a shipped paywall name the location and build in the answer, marked source: "bundled", and its analytics events carry packageSource: "bundled". Every paywall's events carry packageSource: network, cache or bundled.

A paywall package larger than 16 MB isn't loaded. A paywall shows images from https addresses on the internet only, never from the device itself or its local network, nor from an address with a user name or password, and follows a redirect only to such an address. It skips an image larger than 10 MB, an embedded data: image included. Studio reports a typed image address devices refuse, and a debug build also loads images from the development server it is configured with. Your Voidhash server, the one baseUrl names, is always allowed over https whatever its address, and so are images uploaded to your project. An image too large to decode safely, over 4096 pixels on a side, is scaled down; one declaring more than 8192 × 8192 pixels isn't shown. An image uploaded to your project shows only when its bytes are the ones recorded when it was uploaded: one that differs fails like any other image, isn't kept, and is reported once per image and build each time the app runs as $paywall_image_integrity_failed.

The images a paywall shows are kept on the device too, up to 64 MB, so a paywall shown or preloaded before has them while their host can't be reached. Only PNG, JPEG, WebP and GIF images are kept. The SDK fetches them ahead when it loads a paywall for a presentation or a preload, except on cellular, on a personal hotspot or in Low Data Mode. A kept image isn't downloaded again, so publish changed artwork under a new URL.

Preload locations

The SDK remembers up to 20 locations the device has presented and downloads their paywalls at launch. To have paywalls ready on the very first launch, list their location slugs:

options.preloadLocations = ["onboarding"]

A location listed in options.flowRevisions is preloaded for that revision.

Language

Each paywall text, image and property is shown in the device's first preferred language (Locale.preferredLanguages.first) when the paywall has a translation for it. An exact match such as pt-BR wins, then the language alone (pt), then the paywall's base content. A paywall translated only to pt-BR doesn't serve pt devices. Prices are formatted by the App Store. See Translate a paywall.

Analytics

Each presentFlow call that gets a paywall to show records exactly one of these, with loadDurationMs (from the call until then). Every event about a paywall, its own included, carries packageSource once its build is loaded, so a load that fails before then has none: network, cache or bundled (a paywall you ship with the app):

EventWhenPropertyValues
$paywall_viewedThe paywall's first frame was drawn.
$paywall_load_failedIt failed before its first frame.reasonpackage_download_failed, package_integrity_failed, package_unsupported, render_failed, timeout, other
$paywall_load_cancelledIt was given up on before its first frame.cancelledByapp, end_user (the loading screen's close button or the VoiceOver escape gesture)

A viewed paywall then records how it ended, unless the app is terminated first:

EventWhenPropertyValues
$paywall_completedThrough its end step, or a purchase or restore that ends it.completionend_step, purchase, restore
$paywall_dismissedAny other way: its close button, your app, or an error drawing it.reasonclose, app, error

$paywall_viewed also carries the screen the paywall opened on, as flow_screen_index and flow_screen_name, and productsUnavailable: true when it was shown although its products couldn't be loaded. A paywall that closes before it was viewed records $paywall_load_cancelled, never a view.

VoidhashUI presents a paywall full screen, so the user leaves it only through the paywall itself. When your app, or the system, takes it off the screen, $paywall_load_cancelled says cancelledBy: app and $paywall_dismissed says reason: app. Apart from the loading screen's close button and the VoiceOver escape gesture, end_user and system appear only with a custom presenter that lets the user dismiss the paywall (endUserCanDismiss). A load that fails while a build's runtime downloads or starts is reported as render_failed.

A purchase in a paywall that carries on, such as an onboarding flow, isn't an ending. A presentFlow call that throws .notAssigned, .rendererMissing or .disabled, or .unavailable because the location was never loaded and Voidhash can't be reached, records nothing, and so does preloading. A retry is a presentation of its own. The events are queued like any other: one reported offline is sent later, once.

getPaywall(location:) and getPaywallState(location:) hand the paywall to your app. When an A/B test chose it, each call that returns it records $paywall_handed_off, which counts the person in the test: also a call made only to see what the location shows.

These events, $paywall_handed_off, the ones a paywall tracks itself and each screen it shows, which is recorded as a $screen event, carry paywall_location, paywallId, paywallLocationId, paywallShowingId and paywallReleaseId. An intercepted close attempt records $paywall_close_intercepted. Without analytics consent none of them is recorded.

A purchase made on a paywall is credited, with its renewals, to the location, paywall, build and A/B test variant. Purchases made outside a paywall, restores, and Ask to Buy purchases approved after the paywall closed aren't credited to a paywall. A/B tests have no SDK API: Voidhash picks the variant when the location resolves, and the person is counted in the test when the SDK presents the paywall (whether it appears, fails or is given up on) or hands it to your app, not when it is only preloaded or refreshed. See A/B tests on paywalls.

Embed a paywall view

FlowView is the UIView the renderer presents. It draws a paywall package and exchanges messages with its host. Apps don't need it: presentFlow handles presentation, purchases and analytics. Use getPaywall(location:) and the view only to build your own presenter. A paywall you present yourself is counted in its A/B test when getPaywall hands it to you, but records none of the presentation events above.

Next steps

Something wrong or missing on this page? Tell us by email or on Discord.