Skip to content
Optima docs
SDKsiOS SDK

API reference

iOS SDK v1.4.0 — API reference

Everything is reachable from Optima.shared after Optima.initialize(config) has run. Optima.shared: OptimaClient never throws and is never optional: before initialize (or if it failed), it's an inert disabled client — every method a no-op, every stream empty, deviceId == "", one warning logged the first time it's touched. Every method on the live client is guarded internally (OptimaRuntime.guarded): a thrown or unexpected internal error becomes an .error(op, cause) event, never an exception that propagates into your app.

Threading

Every public method returns immediately — nothing blocks the calling thread. track/screen/captureURL/reset/consent.setKeys/setGCM/ setTCF/nba.respond/push.setToken/content.report/content.refresh enqueue work and return Void. identify(_:attributes:) and consent.set(_:meta:) return a @discardableResult Task<Void, Never> you can await if you want to know when the network round trip finished, or ignore entirely — the SDK drives it to completion either way. content.fetch(slot:) and forms.load(id:lang:) are plain async functions. Every listener — addListener, consent.observe, ContentSlot.observe, AsyncStream consumers of events/changes/updates — is called on the main dispatcher (DispatchQueue.main on Darwin), so it's always safe to touch UI state directly from inside one, exactly like the Android SDK's Handler(Looper.getMainLooper()) posting and the Web SDK's browser-thread callbacks.

Optima

enum Optima {
    static var isInitialized: Bool { get }
    static var shared: OptimaClient { get }
    static func initialize(_ config: OptimaConfig)
    static func track(_ category: String, name: String? = nil, props: [String: Any]? = nil)
    static func screen(_ name: String, props: [String: Any]? = nil)
}

Optima.initialize builds the runtime on real platform ports (Platform.makeRuntime). A second call is a no-op with a warning — the first configuration always wins, matching the Android and Web SDKs' "first config wins" rule. The static Optima.track/Optima.screen convenience functions exist so a call site that hasn't captured Optima.shared yet still works before initialization completes on another thread: they read the runtime if one exists, or log one "used before initialize" warning and drop the call, exactly the same fallback the disabled client gives you through Optima.shared.

OptimaClient

protocol OptimaClient: AnyObject {
    var config: OptimaConfig { get }
    var deviceId: String { get }
    func track(_ category: String, name: String?, props: [String: Any]?)
    func screen(_ name: String, props: [String: Any]?)
    func captureURL(_ url: URL)
    @discardableResult func identify(_ identifiers: [String: String], attributes: [String: Any]?, assertion: IdentityAssertion?) -> Task<Void, Never>
    func reset()
    func flush() async
    func addListener(_ l: @escaping (OptimaEvent) -> Void) -> OptimaSubscription
    var events: AsyncStream<OptimaEvent> { get }
    var consent: ConsentApi { get }
    var content: ContentApi { get }
    var forms: FormsApi { get }
    var nba: NbaApi { get }
    var push: PushApi { get }
}

Default-argument extension overloads let you drop the trailing parameters: track(_:), track(_:name:), screen(_:), identify(_:), identify(_:attributes:).

track(_:name:props:)

optima.track("add_to_cart", name: "sku-123", props: ["price": 19.99]). category is required (1–128 characters, or the call is dropped with a debug log and never reaches the outbox — this is a local, synchronous validation, not a server round trip). Builds one hit with a fresh message_id, the current session id (minting a new session and setting session_start: true if none is active or the previous one went idle for more than 30 minutes — SessionManager), and enqueues it into the on-disk outbox (Internal/Tracker.swift). Hits coalesce into batches of 20, flushed after a 2 second debounce or immediately once a batch fills; a 429/5xx response backs off on the ladder 1s → 2s → 5s → 15s → 60s (or the server's Retry-After header, whichever is more specific) and a terminal 4xx drops the batch and emits .error(op: "track", cause:). A successful flush emits .track(accepted:dropped:hits:).

screen(_:props:)

optima.screen("ProductDetail") — a thin wrapper that sets the SDK's current screen name (read by every content fetch's screen/url query parameters, chapter 5) and then calls track("screen_view", name: name, props: props) with the tracking context's url/title fields populated from the screen name. This is the one call every install should make either manually or via screenTracking = .auto (chapter 2) — see chapter 2's category mapping for why an unmapped screen_view category silently drops on the server.

captureURL(_:)

optima.captureURL(url) — the universal-link / custom-scheme attribution hook (there is no install-referrer equivalent on iOS, see chapter 8). Extracts utm_source/utm_medium/ utm_campaign/utm_term/utm_content/gclid/fbclid from the URL's query string and persists them (_optima_utm); every subsequent screen() call merges them into its props. First capture wins for the life of the process (cleared only by reset()); a URL with none of those keys, or a second call after one already succeeded, is a silent no-op.

identify(_:attributes:assertion:)

optima.identify(["email": "a@b.com"], attributes: ["plan": "pro"]) — posts identifiers and/or attributes to POST /edge/v1/identify under the device's current consent declaration, with a 5-attempt retry ladder (Internal/Identifier.swift, same 1s/2s/5s/15s/60s backoff as tracking). An identifier nobody owns yet is attached to this device; an identifier another customer already owns is NOT attached — it is recorded as an unverified claim for identity rules — unless you also pass assertion, an IdentityAssertion minted by your backend with the SDK key's identify secret, which proves the visitor holds it. A call with identifiers, attributes and assertion all empty/nil is a local no-op (nothing to send, not even a network call). Emits .identify(accepted:dropped:) on a 2xx response, or .error(op: "identify", cause:) once the retry budget is exhausted or a terminal 4xx comes back (including an invalid or expired assertion). push.setToken calls this internally with push_token_apns, so you rarely call it for that purpose yourself.

reset()

Call on logout, or whenever a shared/kiosk device changes hands. Rotates deviceId to a fresh UUID, clears the on-disk outbox, the consent store, the session, captured attribution, and content "seen"/dismiss memory, then runs every component's reset hook: the content engine clears every declared slot's presentations and bumps its fetch generation (in-flight fetches from before the reset can never resurrect stale data — chapter 5), the tracker gate's inventory cache invalidates for a forced refetch, and — as one of the last steps — if an APNs token was previously set, it's re-attached via identify under the new device id (the physical device hasn't changed, only the person using the app; see chapter 7 for the shared-device opt-out). Never throws; a storage failure mid-reset is caught and logged like every other guarded call.

flush()

await optima.flush() drives one batch of the tracking outbox through immediately — useful right before you expect the process to be suspended (the SDK also does this automatically on background, via the app lifecycle observer) or in a test/debug flow where you don't want to wait out the 2 second coalesce window. It's async and returns once that one batch's network attempt (success, terminal failure, or the start of a backoff wait) has been made; a fuller outbox needs a second flush() call, exactly like the internal auto-flush loop.

addListener(_:) / events

let sub = optima.addListener { event in ... }
sub.cancel()   // idempotent — cancelling twice is harmless

for await event in optima.events { ... }   // current + future events, main-actor delivery

OptimaSubscription.cancel() is the unsubscribe call every observer-style API in the SDK returns (addListener, consent.observe, ContentSlot.observe, ContentApi.observeDeclaredSlots). .ready(version) replays to a listener that attaches after the SDK already finished initializing, so a late subscriber never misses it.

deviceId

A UUID minted once by DeviceId and persisted in UserDefaults under _optima_did — never a hardware identifier, never derived from IDFA/IDFV. Stable across app restarts; rotated only by reset().

Events

enum OptimaEvent {
    case ready(version: String)
    case track(accepted: Int, dropped: [[String: String]], hits: Int)
    case identify(accepted: Int, dropped: [[String: String]])
    case consentChange(state: ConsentState)
    case consentRevoked(purposes: [String])
    case contentLoaded(slot: String, count: Int)
    case contentItem(slot: String, item: ContentItem)
    case formSubmitted(id: String, dropped: [String], doubleOptIn: Bool)
    case trackerFired(name: String, kind: String)
    case error(op: String, cause: Error?)
}
CaseFires when
.readyThe runtime finished constructing (replayed to late listeners).
.trackA tracking batch received a 2xx response.
.identifyAn identify call received a 2xx response.
.consentChangeAny consent.set/setKeys/setGCM/setTCF call, or reset() clearing consent back to an undecided ConsentState().
.consentRevokedA consent.set(...) call flips a previously-true purpose to false.
.contentLoadedA content fetch resolves for a slot — count excludes platform-inapplicable items (web_personalization) and items diverted into a .contentItem event instead.
.contentItemA content item can't become a Presentation on this platform (an unregistered structured type, an unstructured item while htmlMode == .off, or banner_consent under consent.source == .cmp) — surfaced as raw data for you to handle. web_personalization items are excluded from this too: they're dropped silently (one debug line), never emitted as .contentItem.
.formSubmittedA form submit accepts (including the 409-means-success case, chapter 6).
.trackerFiredA pixel-kind managed tracker fires (gated by consent.can, chapter 4).
.errorAny guarded operation fails — check cause for detail; a terminal HTTP body is truncated to 200 characters in the debug log line next to it.

ConsentApi

protocol ConsentApi: AnyObject {
    func get() -> ConsentState
    @discardableResult func set(_ decisions: [String: Bool], meta: ConsentMeta? = nil) -> Task<Void, Never>
    func setKeys(_ keys: [String: Bool])
    func setGCM(_ g: [String: GcmValue])
    func setTCF(_ tc: String)
    func can(_ trackerName: String) -> Bool
    func observe(_ cb: @escaping (ConsentState) -> Void) -> OptimaSubscription
    var changes: AsyncStream<ConsentState> { get }
}

consent.get() returns the current ConsentState synchronously (no network call — it's the persisted local store). consent.set(_:meta:) writes locally, emits .consentChange/.consentRevoked, unblocks a .buffered tracker if this is the first decision, and posts the decision to POST /edge/v1/consent in the background Task it returns. consent.setKeys, consent.setGCM and consent.setTCF feed vendor-signal passthrough (CMP/GCM/TCF) without touching the SDK's own decisions map. consent.can(name) checks a tracker-inventory entry's purpose against the current decision (fail-closed false for an unknown name or before the inventory has loaded). consent.observe/consent.changes deliver the current value immediately, then every subsequent change. Full detail: chapter 4.

ConsentState: v: Int, decisions: [String: Bool], decidedAt: Int64?, bannerId: String?, policy: [String: String]?, lang: String?, plus the computed decided: Bool (decidedAt != nil) and granted: [String] (sorted keys currently true). ConsentMeta: bannerId, lang, policy — optional metadata a consent decision can carry back to the server, mirroring what the built-in banner sends.

ContentApi (headless)

protocol ContentApi: AnyObject {
    var overlaySlot: String { get }
    func slot(_ name: String) -> ContentSlot
    var declaredSlots: [String] { get }
    func observeDeclaredSlots(_ cb: @escaping ([String]) -> Void) -> OptimaSubscription
    var declaredSlotsUpdates: AsyncStream<[String]> { get }
    func fetch(slot: String) async -> [ContentItem]
    func report(_ presentation: Presentation, action: ContentAction)
    func refresh()
    func register(type: String, renderer: Any)
    func rendererFor(type: String) -> Any?
}

content.slot(name) declares a slot (fetching it if this is the first call for that name) and returns a live ContentSlot — .current: [Presentation] plus .observe(_:)/.updates: AsyncStream<[Presentation]>. content.declaredSlots lists every slot declared so far in this process; content.observeDeclaredSlots { names in … } and its async-sequence twin content.declaredSlotsUpdates (for await names in content.declaredSlotsUpdates) deliver the current list immediately and again whenever a new slot is declared — the same callback/AsyncStream pairing ContentSlot uses. content.fetch(slot:) is a one-shot fetch that declares nothing and applies no display rules — you own targeting, frequency and placement entirely. content.report(presentation, action:) records .impression/.click/ .dismiss feedback (deduped, batched to the server). content.refresh() re-fetches every declared slot immediately (the built-in consent banner removes itself locally on a decision and calls this once the consent POST has completed — server-side suppression is eventually consistent, see chapter 4). content.register(type:renderer:) is the untyped registration entry point the OptimaSDKUI module's register(type:_:) convenience (below) wraps — call the typed one from app code. Full detail: chapter 5.

Types: Presentation (slot, item: ContentItem, placement: DisplayRule.Placement, dismissible: Bool, computed key), ContentItem (id, type, format ["structured" | "unstructured"], payload: [String: Any]?, html: String?, priority, origin, channel, token, campaignDisplay: CampaignDisplay?, computed isCampaign and display: DisplayRule), DisplayRule (placement: Placement? — absent defaults to .overlay, see chapter 5 —, position, style, trigger: Trigger, frequency: Frequency, dismissible: Bool?, ttlDays: Int?).

FormsApi

protocol FormsApi: AnyObject {
    func load(id: String, lang: String?, assertion: IdentityAssertion?) async -> FormResult
    func pageURL(_ url: URL) -> URL
}

forms.load(id:lang:assertion:) (or the load(id:lang:) / load(id:) overloads, which pass no assertion) fetches a form definition and returns a FormResult: .loaded(FormDefinition, submit: ([String: Any]) async -> SubmitResult), .notFound, or .failed(status: cause:). The bound submit closure already carries the render nonce and honeypot internally. forms.pageURL(url) appends device_id to a hosted page URL so a browser-completed form and a native identify(...) call resolve to the same profile. FormDefinition: id, slug, name, lang, fields: [FormField], successMessage, successRedirectUrl, doubleOptIn, minSubmitIntervalSec. SubmitResult: .accepted(dropped: [String], doubleOptIn: Bool), .rejected(status: Int, message: String), .failed(cause: Error?). Pass assertion (the backend-minted IdentityAssertion that identify(_:attributes:assertion:) takes) when a logged-in visitor fills the form: the bound submit sends it, and it must vouch for an identifier field the submission carries, or the gateway answers 400 invalid_assertion (.rejected). Full detail: chapter 6.

NbaApi

protocol NbaApi: AnyObject { func respond(nbaId: String, action: NbaAction, extra: NbaExtra? = nil) }
enum NbaAction: String { case presented, accepted, postponed, rejected, realized }

nba.respond(nbaId:action:extra:) records a customer's response to a Next-Best-Action recommendation your app rendered. nbaId must be exactly 26 characters (the backend's ULID-shaped identifier) or the call is dropped locally with a debug log. Responses batch (50 per batch, 1 second coalesce) to POST /edge/v1/nba/responses with the same backoff ladder as tracking. A single 404 disables the queue for the rest of the process (the operator's kill switch — chapter 9). NbaExtra: optional reason, referenceId, value.

PushApi

protocol PushApi: AnyObject {
    func setToken(_ deviceToken: Data?)
    func setToken(hex: String?)
    func parse(_ userInfo: [AnyHashable: Any]) -> OptimaPush?
    func trackOpen(_ userInfo: [AnyHashable: Any]) -> Bool
}

push.setToken(_:) takes the raw Data token from application(_:didRegisterForRemoteNotificationsWithDeviceToken:), hex- encodes it, and — if new or changed — calls identify(["push_token_apns": token]). push.setToken(hex:) is the string-keyed overload; nil forgets the token locally without notifying the server. push.parse(_:) reads a notification's userInfo for the SDK's reserved keys (deep_link, buttons, optima_open, image_url) and returns an OptimaPush, or nil if none of them are present (not an Optima-sent push). push.trackOpen(_:) fires GET /edge/v1/o/{token} fire-and-forget when optima_open is present, returning whether it was — safe to call unconditionally on every launch. Full detail: chapter 7.

OptimaSDKUI

The SwiftUI module built on top of OptimaSDK. Every type here is compiled only under #if canImport(UIKit) && canImport(SwiftUI), so the module is available on iOS only.

public struct OptimaHost: View { public init(client: OptimaClient = Optima.shared, theme: OptimaTheme = .system()) }
public struct OptimaSlot: View { public init(_ name: String, client: OptimaClient = Optima.shared, theme: OptimaTheme = .system()) }
public protocol OptimaRenderer { associatedtype Body: View; func render(_ presentation: Presentation, actions: RenderActions) -> Body }
public struct AnyOptimaRenderer { public init<R: OptimaRenderer>(_ r: R) }
public extension ContentApi { func register<R: OptimaRenderer>(type: String, _ renderer: R) }
public struct OptimaTheme { public var surface, onSurface, primary, onPrimary: Color; public var cornerRadius: CGFloat; public static func system() -> OptimaTheme }
public extension View {
    func optimaScreen(_ name: String, props: [String: Any]? = nil, client: OptimaClient = Optima.shared) -> some View
    func optimaImpression(minVisible: CGFloat = 0.5, dwell: TimeInterval = 1, _ onImpression: @escaping () -> Void) -> some View
}

OptimaHost() — place once, near your app's root — draws every overlay- placement presentation from every declared slot plus the implicit __overlay slot (banners, the consent UI, campaign onsite modals). OptimaSlot("name") declares a slot and renders its inline presentations in place. OptimaRenderer is the protocol you implement for your own structured content types and register with the typed content.register(type:_:) overload (prefer it over the untyped ContentApi.register(type:renderer:) — only an AnyOptimaRenderer can actually be dispatched to, and this overload is the one that guarantees it); AnyOptimaRenderer is the type-erased box the registry stores. RenderActions (onImpression, onClick, onDismiss, openURL) is what a renderer's render(_:actions:) is handed to report feedback and navigate. OptimaTheme.system() is the default look (system colors plus the app's accent color) both OptimaHost and OptimaSlot fall back to. .optimaScreen(name) is the SwiftUI equivalent of a manual screen(name) call, fired on onAppear. .optimaImpression(minVisible:dwell:_:) is the visibility-timing modifier every built-in renderer (BannerView, InAppView) uses to report an impression once a view has been at least 50% visible for 1 second — use it directly in your own custom renderers if you want the same timing rule content feedback everywhere else in the SDK relies on. Full detail: chapter 5.

On this page