MonetizationOS Docs
Getting StartedIntegrate with MOS

iOS SDK

The MonetizationOS iOS SDK lets a native app call MonetizationOS directly with a public key. It requests a surface decision for the item a user opens, answers access and meter questions from the features in the response, shows native or web paywalls, and keeps working offline from a decision cache and a queue of unsent meter updates.

To call the Surface Decision API yourself without the SDK, follow the iOS recipe instead.

View on GitHub

Prerequisites

  • A MonetizationOS environment with a configured surface and a feature for the app to check.
  • A public key. In the console, open your environment's API Keys screen and select New Public Key under Public Keys. The SDK refuses any key that doesn't start with pk_, because a secret key must never ship in an app.
  • iOS 18 or later, and Xcode 26 or later.

Install

Add the package with Swift Package Manager. In Xcode, choose File > Add Package Dependencies, enter https://github.com/MonetizationOS/mos-ios-sdk, and start from version 0.9.0. In a Package.swift file:

Package.swift
dependencies: [
    .package(url: "https://github.com/MonetizationOS/mos-ios-sdk", from: "0.9.0"),
],
targets: [
    .target(
        name: "MyApp",
        dependencies: [
            .product(name: "MonetizationOS", package: "mos-ios-sdk"),
            .product(name: "MonetizationOSUI", package: "mos-ios-sdk"),
        ]
    ),
]
ProductContents
MonetizationOSDecisions, identity, the offline cache, metering, and offer redemption.
MonetizationOSUIMOSWebPaywallView, which shows a web paywall in a web view. Add it only if you use web paywalls.

The SDK is pre-1.0, and a minor release can include breaking changes. To take patch releases only, use .upToNextMinor(from: "0.9.0"), and read the changelog before you upgrade. Failure reasons, redemption actions, experience kinds, property types, and decision sources can gain cases in a minor release, so end each switch over them with @unknown default:.

Quick start

Create one MOS client at launch and keep it for the life of the app. Clients with keys for the same environment use the same cache, queue, and meter files and Keychain entries, so two of them overwrite each other's. Creating the client throws MOSError.invalidPublicKey for a key that isn't public.

import MonetizationOS

let mos = try MOS(config: MOSConfig(
    publicKey: "pk_live_...",
    surface: "mobile-app",
    app: .init(name: "ExampleNews", version: "1.0")
))

surface is the slug of the surface the app uses by default. app names your app and its version, which the SDK sends in the User-Agent header so that app traffic is distinguishable from web traffic in observability. A blank name or version is sent as app.

While you integrate, pass onLog: consoleLogger to MOSConfig to print each request, cache hit, and failure.

Run a decision for the item the user is looking at, then check access:

let result = await mos.decide(resource: Resource(id: "article/123", meta: ["section": "sport"]))

if result.hasAccess(feature: "article", property: "enabled") {
    // Show the article.
} else {
    // Show a paywall.
}

Resource.id identifies the item. A meter set to Unique Resources counts each distinct id once. meta is a dictionary of strings that your workflows can read.

hasAccess(feature:property:) returns a meterable property's hasAccess, or a boolean property's value. With no decision, a missing property, a boolean property that has no value, or a property of another type, it returns the failOpen setting described under Offline and metering.

decide never throws. Failures come back in the result as result.failure, and result.source says where the decision came from. decide, redeem, and flush run to completion even if the calling task is cancelled. A decision consumes the meters it counts against, so decide once per item the user opens and reuse the result for every check. The SDK never retries a decision, because a retry could consume a second unit, and identical decisions already in flight share one request.

To use a different surface for one call, pass surface:. To send extra context to your workflows, pass properties:, which workflows read as context.properties. The SDK adds the property platform, set to ios, to every decision.

To run only some of the surface's components, pass components: with their slugs. An empty list runs the surface workflow alone, and leaving it out runs every component. Each selection has its own cache entries.

Read surface properties

Your surface workflow can return open JSON under properties. The SDK exposes it as JSONValue, and the shape is yours to define:

if let banner = result.decision?.surfaceProperties["banner"],
   let text = banner["text"]?.stringValue {
    // Draw the banner natively.
}

Properties from a component workflow are in decision.componentBehaviors[slug]?.properties. For a meter, match the typed property to read its units:

if case .meterable(let meter)? = result.decision?.features["article"]?.properties["views"] {
    let remaining = meter.remainingUnits // Double?
}

Sign users in

Until a user signs in, the SDK identifies them by an anonymous identifier. The first decision asks MonetizationOS to mint one, and the SDK stores it in the Keychain and sends it on every later call. Meters and grants for a signed-out user attach to it.

If several decisions start at once on a fresh install, each asks MonetizationOS for an identifier, and the SDK keeps only the first one that comes back. Meters counted against the others don't follow the user. If the Keychain doesn't keep the identifier, the SDK logs identity:store-failed and uses the identifier from memory until the app quits, so it doesn't ask for a new one on every decision.

To identify a signed-in user, give the SDK their JWT. Your JWT integration validates it on the server. For each call, the SDK picks the identity in this order: the token from identify(userJWT:), the token from jwtProvider, the stored anonymous identifier, and finally a new anonymous identifier from the server.

jwtProvider is the simplest option. The SDK calls it before every decision, redemption, and flush, so it should return the current token quickly and refresh it when needed:

let mos = try MOS(config: MOSConfig(
    publicKey: "pk_live_...",
    surface: "mobile-app",
    app: .init(name: "ExampleNews", version: "1.0"),
    identity: .init(
        jwtProvider: {
            do {
                return try await auth.freshAccessToken()
            } catch AuthError.signedOut {
                return nil
            } catch {
                return auth.lastAccessToken
            }
        },
        claimKey: "sub" // The JWT Claim Key of your JWT integration.
    )
))

auth stands for your own authentication layer. Set claimKey to the JWT Claim Key of the integration that validates these tokens. It defaults to sub. The SDK keys a signed-in user's cached decisions and queued meter updates by that claim's value, a string or a number, so a refreshed token for the same user keeps them. A token without the claim is keyed by the whole token, so every refresh looks like a new user: the SDK clears the cached decisions and can drop queued meter updates.

If you would rather push tokens, call identify(userJWT:) after sign-in and again with nil after sign-out. It resolves the identity immediately without a network call, and returns an IdentifyResult with changed, previous, current, and linkPending:

await mos.identify(userJWT: token) // after sign-in, and at every launch while signed in
await mos.identify(userJWT: nil)   // after sign-out

The SDK doesn't persist the token you pass to identify(userJWT:). While a user stays signed in, call it at every launch before any other SDK call. Otherwise the first call runs anonymously, which clears the user's cached decisions and can drop their queued meter updates. jwtProvider doesn't have this problem, because the SDK asks it for the token on every call.

When a token refresh fails for a transient reason, such as no connectivity, return the last token you have. Return nil only when the user is signed out. A nil makes the SDK treat the user as signed out for that call, which switches to the anonymous identity, clears their cached decisions, and can drop their queued meter updates at the next flush.

What happens to the anonymous identifier

When the identity changes from the anonymous identifier to a JWT, the SDK clears the cached decisions, which belong to the old identity, and remembers the anonymous identifier as the previousAnonymousIdentifier. The next decision carries it as properties.previousAnonymousIdentifier. A surface workflow reads it as context.properties.previousAnonymousIdentifier and can link the two identities with utils.identity.link, so usage and grants from before sign-in follow the user. MonetizationOS doesn't link them on its own, so without that call nothing carries over. See Link Identities for the link call.

The SDK keeps the identifier, even across app launches, until a decision that carries it comes back authenticated. A token the server rejects, such as an expired one, gets an anonymous decision instead, so the SDK sends the identifier again with the next decision. result.linkedAnonymousIdentifier is true on the result that delivered it to your workflow. The identifier goes to the first account only. If the user signs straight into a different account before a decision delivers it, the SDK drops it.

After sign-out, the SDK goes back to the stored anonymous identifier and clears the cached decisions again. The next account to sign in gets that identifier as previousAnonymousIdentifier too, even if an earlier account already linked it. To forget the anonymous identifier, the cache, and the queue, so that the device starts as a new visitor, call reset(), for example after sign-out.

The SDK sends signed-in decisions with a fallback to anonymous, so a token the server rejects produces an anonymous decision, not an error. This applies to decisions only: redeem and flush fail with unauthorized instead. Check result.decision?.identity.isAuthenticated if the app needs to know which identity answered. The SDK doesn't cache an anonymous answer to a signed-in request or update meter counts from it, so the user's own cached decisions stay in place, and it logs cache:skipped.

Offline and metering

The SDK caches every successful decision per surface, identity, resource, and component selection. An entry lives for offline.ttl, which defaults to 24 hours, or until the earliest offer token inside it expires, whichever comes first. That includes the offer tokens in a web paywall's HTML. The cache holds up to offline.maxEntries entries, 50 by default. It never stores JWT claims, and its files are excluded from device backups.

offline: .init(ttl: .seconds(24 * 60 * 60), failOpen: true)

The SDK keeps its data per environment, the environment your public key belongs to. Files go in Application Support/com.monetizationos.sdk/<environment>/ and the anonymous identifier in the Keychain service com.monetizationos.sdk.<environment>, so a staging key and a production key in the same app never share an anonymous identifier, cache, queue, or meter counts. On macOS, both also include the app's bundle identifier, because apps outside the sandbox share them.

When a request fails, decide serves the exact cached entry for the resource. Without one, and with fallbackToLatest on, which is the default, it serves the latest entry for the same surface, identity, and component selection. result.source says which happened:

result.sourceMeaning
.networkA fresh decision from MonetizationOS.
.cache(ageMs:)The cached decision for this resource, ageMs milliseconds old.
.fallback(ageMs:fromResourceID:)The latest cached decision for the surface and identity, made for a different resource.
.unavailableNo decision. result.decision is nil, and hasAccess returns failOpen.

result.failure is set whenever the network was tried and failed, even if the cache served the result.

Fail-open. With no decision, hasAccess returns offline.failOpen, which defaults to true. Set it to false to deny access when the app can't get a decision. The setting applies to the whole client, so check result.source where one screen needs a stricter rule. Set fallbackToLatest: false if answering from another resource's decision is wrong for your app.

To choose per call, pass policy: to decide: .networkFirst, which is the default, .cacheFirst(maxAge:), .networkOnly, or .cacheOnly. After an event that changes what the user can access, call clearCache() to drop the cached decisions for every identity.

A cache entry matches on surface, identity, resource id, and component selection only. properties, meta, and other resource fields aren't part of the match, so .cacheFirst and the fallback to the exact entry can return a decision made with different values.

Metering offline

A decision served from the cache stands in for a request that would have consumed meters, so the SDK queues a counter update for each meter that decision consumed. flush() sends the queue, oldest first, and returns a FlushResult with sent, dropped, remaining, and failure. A successful network decision also flushes in the background when updates are queued, so an online session needs no explicit call.

Call flush() when the app comes to the foreground and when connectivity returns:

struct RootView: View {
    let mos: MOS
    @Environment(\.scenePhase) private var scenePhase

    var body: some View {
        ContentView()
            .onChange(of: scenePhase) { _, phase in
                if phase == .active {
                    Task { await mos.flush() }
                }
            }
    }
}

The queue holds up to 500 updates, and it discards updates older than seven days and updates that belong to a user who has signed out. Concurrent calls to flush() share one flush. An update whose request timed out stays queued and is sent again, so if the first attempt reached MonetizationOS, a meter without Unique Resources counts that read twice.

Meter counts offline

Each network decision records the count of every meter in it. Until the next network decision, a meter in a decision served from the cache shows that count plus the reads the device has counted since, so remainingUnits keeps going down offline. A meter set to Unique Resources counts each resource once.

To turn access off when those reads use a meter up, set enforceMeters to true:

offline: .init(enforceMeters: true)

A locked meter has hasAccess set to false and lockedOffline set to true, and the SDK queues nothing for that read. A resource already counted in the current period stays open, even once the meter is used up. That's more lenient than online, where a used-up meter turns access off for every resource.

The cached decision is the one that granted access, so it has no paywall for the locked state. Show your own screen, or cache one from a surface of its own while the app is online and read it back with .cacheOnly. Like every cached decision, it expires after offline.ttl.

// Online, now and then: cache the offline-limit screen.
_ = await mos.decide(resource: Resource(id: "offline-limit"), surface: "offline-limit")

// Offline, when a read comes back locked:
if case .meterable(let meter)? = result.decision?.features["article"]?.properties["enabled"], meter.lockedOffline {
    let limit = await mos.decide(resource: Resource(id: "offline-limit"), policy: .cacheOnly, surface: "offline-limit")
    // Show the experience in limit.decision.
}

Until the next network decision, the device can't see a meter's period reset or reads on other devices, so offline the count can run out early or late.

Paywalls

A workflow resolves an experience and returns it under a property key of its choice. decision.experience(_:component:) reads it from surfaceBehavior.properties[key], or from a component's properties when you pass component:. It returns an Experience, or nil when the key holds no experience, for example when the user already has access.

  • .native comes from an App experience that your workflow resolves with experiences.resolveAsJson. Your app renders its JSON and its offers.
  • .web comes from an HTML experience that your workflow resolves with experiences.resolveAsWebContent. The server renders the HTML, and MOSWebPaywallView shows it.

Native paywall

A native experience holds your own JSON plus its offers. Decode the JSON into your own type, and redeem an offer with redeem(offerToken:) when the user taps it. redeem never throws and returns a RedemptionResult:

import MonetizationOS
import SwiftUI

struct PaywallCopy: Decodable {
    let headline: String
    let body: String?
}

struct NativePaywall: View {
    let mos: MOS
    let experience: Experience
    @Environment(\.openURL) private var openURL

    var body: some View {
        let copy = try? experience.decode(PaywallCopy.self)
        VStack(alignment: .leading, spacing: 12) {
            Text(copy?.headline ?? "Subscribe")
            ForEach(experience.offers.compactMap(\.offer), id: \.id) { offer in
                Button(offer.presentation["title"]?.stringValue ?? offer.id) {
                    Task { await redeem(offer) }
                }
            }
        }
    }

    private func redeem(_ offer: Offer) async {
        switch await mos.redeem(offerToken: offer.token) {
        case .redeemed(.navigate(let url, _), _, _):
            // The org's workflow picks this URL: open only the web and your own app's scheme.
            if ["http", "https", "exampleapp"].contains(url.scheme?.lowercased()) { openURL(url) }
        case .redeemed(.custom(let type, let properties), _, _):
            startPurchase(type: type, properties: properties) // Your own code, e.g. custom:storekit: buy with StoreKit.
        case .redeemed(.noAction, _, _):
            await refreshDecision() // Decide again so the screen reflects the new access.
        case .declined(let message, _, _):
            showMessage(message) // The workflow refused the redemption.
        case .failed:
            showRetry() // It may not have run. For a timeout or server error it may have, so check before retrying.
        @unknown default:
            await refreshDecision() // A case added in a later release.
        }
    }
}

A redeemed offer clears the decision cache, as clearCache() does, so the next decision comes from MonetizationOS with the new access. An action of type custom, or of a custom: type such as custom:storekit, arrives as .custom with that type. A navigate action's URL comes from your organization's redemption workflow, so open it only if it's http, https, or your own app's scheme.

offer.presentation is whatever JSON your organization gave the offer. offer.storeProductID is its presentation.storeProductId, so you can look up the store's localized price with StoreKit. Identical redemptions in flight, such as a double tap, send once and share the result.

Web paywall

Show a web experience with MOSWebPaywallView from MonetizationOSUI. It takes the HTML, the client, and callbacks for the two ways the page can finish:

import MonetizationOS
import MonetizationOSUI
import SwiftUI

struct WebPaywall: View {
    let mos: MOS
    let html: String
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        MOSWebPaywallView(
            html: html,
            mos: mos,
            priceProvider: StoreKitPrices(),
            onRedemption: { redemption in
                handle(redemption) // Act on the result as for a native paywall.
            },
            onClose: { dismiss() }
        )
    }
}

The page reaches the app only by navigating. A link to mos://redeem?token=... redeems the offer through mos, then calls onRedemption with the RedemptionResult. A link to mos://close calls onClose. An http or https link goes to onOpenURL, which defaults to the system browser. The view blocks everything else. The callbacks run on the main actor. If the web content process ends, the view reloads the page once. If it ends again within 30 seconds, the view calls onClose instead. Both log webpaywall:process-terminated.

In the experience's HTML template, link each plan to its offer token and mark where the store's price goes. storeProductId and fallbackPrice here are presentation fields on the offer, so use the names your offers define:

{{#mos-offer-slots-map.slot-0}}
  <a href="mos://redeem?token={{mos-offer-token}}">
    <span data-mos-product="{{storeProductId}}">{{fallbackPrice}}</span>
    <span data-mos-product="{{storeProductId}}" data-mos-price="display-period"></span>
  </a>
{{/mos-offer-slots-map.slot-0}}
<a href="mos://close">Not now</a>

Any element with data-mos-product has its text replaced with the localized price that your PriceProvider returns for that product, and data-mos-price="display-period" uses the subscription period instead. Elements the provider can't price keep their fallback text. For a button that isn't a link, put data-mos-redeem="{{mos-offer-token}}" on the element.

The price provider answers from your own StoreKit code:

import MonetizationOS
import StoreKit

struct StoreKitPrices: PriceProvider {
    func prices(productIDs: Set<String>) async -> [String: StorePrice] {
        guard let products = try? await Product.products(for: productIDs) else { return [:] }
        return Dictionary(uniqueKeysWithValues: products.map { product in
            (product.id, StorePrice(displayPrice: product.displayPrice))
        })
    }
}

StorePrice also takes displayPeriod and introductoryDisplayPrice.

Call your endpoints

callEndpoint sends a request to one of your environment's endpoints with the public key, so give the endpoint the Public Key access level. The SDK sends no user identity with these calls. If the endpoint's workflow needs to know the user, send their token yourself, for example in an Authorization header, and verify it in the workflow before you trust the request.

let result = await mos.callEndpoint(path: "orders/checkout", body: ["item": .string(itemID)])

switch result {
case .response(let response) where response.isSuccess:
    let order = response.json // JSONValue?; also response.text and response.body
case .response(let response):
    showError(status: response.status) // The endpoint answered with an error status.
case .failed:
    showRetry() // No response arrived. Check failure.reason.
}

Every HTTP response comes back as .response, whatever its status, with status, headers, body, json, text, and isSuccess. .failed means no response arrived, with the reason requestFailed, timeout, or notConfigured. A call whose task is cancelled returns .failed with requestFailed.

The method defaults to .post. Pass method: for .get, .put, .delete, or .patch, and query:, headers:, or timeout: as you need them. Without timeout:, a call gets the full requestTimeout from MOSConfig, 5 seconds by default, even after other requests have timed out. Redemptions do too, so a slow workflow isn't cut short and reported as a timeout. A call with a body and .get or .delete fails without sending. The SDK drops headers it owns, such as X-MOS-Key, User-Agent, and Content-Type, from headers:. To put values such as an id into the path, pass pathSegments: instead of path:, which encodes each segment whole, so "a/b" stays one segment. Endpoint calls are never retried, cached, or merged.

An installed app's endpoints live under the app's namespace. Get a handle with app(namespace:) and call it the same way. The namespace is set when the app is installed, so read it from your configuration rather than hard-coding it:

let orders = mos.app(namespace: installedNamespace)
let recent = await orders.call(path: "orders/recent", method: .get, query: ["page": "1"])

Privacy

The SDK ships a privacy manifest, PrivacyInfo.xcprivacy, as a resource of the MonetizationOS target, so there is nothing to add to your project. It declares:

  • No tracking, and no tracking domains.
  • Two collected data types, both linked to the user, not used for tracking, and collected for app functionality only: User ID, for the anonymous identifier and the subject of a JWT you provide, and Product Interaction, for the resource ids sent with decisions and deferred counter updates.
  • No required-reason API categories.

The SDK reads no advertising identifier and no location. Requests go to the MonetizationOS API over HTTPS. Your app's own privacy manifest and App Store privacy answers still need to cover everything else your app collects.

Example app

The Showcase app in the SDK repository has one SwiftUI screen per use case, such as gating content, metered access, paywalls, offer redemption, sign-in, and offline behavior. It runs on bundled fixtures with no account or key, and a Live mode points it at your own environment. See Examples/Showcase for the source and run steps.

On this page