Skip to content
Optima docs
SDKsiOS SDK

Content

iOS SDK v1.4.0 — Content

Slots and placement

Content is organized into named slots — arbitrary strings your app defines, matching whatever the operator targets in the console (a slot name like "homepage_hero" or "checkout_upsell"). Declare a slot in two ways:

  • SwiftUI: drop OptimaSlot("homepage_hero") where you want inline content to render, and put one OptimaHost() near your app's root to catch overlay-placement content (dialogs, bottom cards) from every slot, plus the implicit __overlay slot used by items with no explicit inline placement.
  • Headless: call Optima.shared.content.slot("homepage_hero") yourself, and render the returned ContentSlot (.current: [Presentation], .updates: AsyncStream<[Presentation]>) however you like — see Headless use.

Every Presentation carries a placement: .inline (render it where you declared the slot — this is what OptimaSlot draws) or .overlay (render it floating above everything — this is what OptimaHost draws). The server's display.placement field decides this per item; when it's absent, the SDK defaults to .overlay.

The no-slot caveat

An .inline-placement item whose slot has no corresponding OptimaSlot anywhere in your view hierarchy renders nowhere. Declaring the slot via content.slot(name) headlessly and then never rendering its updates has the same effect — the item is fetched, counted in .contentLoaded, and then simply has nowhere to go. This is by design (there's no implicit fallback location for an inline item), but it's an easy trap when a new slot is targeted in the console before the corresponding OptimaSlot ships in an app update — the item just silently never appears, with no error anywhere. If you see a .contentLoaded(slot, count > 0) event but nothing on screen, this is the first thing to check.

Screens and URLs

Every screen(name) call sets the SDK's notion of "current screen," which feeds two things: the screen_view tracking hit (chapter 3) and every content fetch's screen/url query parameters. The URL follows a fixed convention: app://<bundle-id>/<screen> — for example, app://com.example.shop/ProductDetail (OptimaRuntime.screenUrl). This exists so the console's existing URL-glob targeting (built for the Web SDK's real page URLs) stays meaningful on mobile without a separate targeting model: an operator can write a URL pattern like app://com.example.shop/Product* and it matches every screen name starting with Product, exactly the way https://shop.example/product/* would match web pages. $context.url in the console's category-mapping and report tooling reads this same value.

Two kinds of content targeting exist server-side and both arrive through this one mechanism: operator-authored items matched by URL glob against this app:// URL, and campaign mobile_inapp items matched by the literal screen name (not a glob) — you don't need to do anything different for either kind, the same slot(name) call surfaces both.

display rules

Every structured content item's payload.display object is parsed into a DisplayRule and applied verbatim, field by field:

FieldValuesBehaviour
trigger.onload | delay | eventload: shown as soon as it resolves from the fetch. delay: shown after trigger.delay_ms milliseconds (capped at 24 h). event: shown the next time track(category) is called locally with category == trigger.event. scroll and exit (web-only concepts with no iOS equivalent) fold to load — there's no DOM to scroll or a tab to exit, so the SDK treats them as "show immediately" rather than dropping the item.
frequency.always | .session | .once | .perDays(N).always: shown every time it's returned. .session: shown once per app session (in-memory only, reset by reset() and process death). .once: shown once ever, remembered in _optima_seen. .perDays(N): shown at most once every N days.
dismissibletrue | false | absentWhether a close control is rendered. Absent falls back to the item's campaign display block (dismissible there) if present, then to "true for .overlay, false for .inline."
ttlDaysintegerAfter a dismiss, the item is suppressed for this many days even if its frequency would otherwise allow it again — dismissal is a stronger, time-bounded "no" than the frequency rule alone.
placement.inline | .overlay | absentSee Slots and placement above; absent defaults to .overlay.
position / styletop/bottom; card/bar/modalCosmetic — read by the built-in OptimaSDKUI renderers (OverlaySlotView picks its alignment from position; InAppView picks a wide modal card vs. a bottom card from style == "modal").

frequency.per_days and ttl_days are capped at 36,500 days: larger values behave as 36,500, and a number too large to be an integer (above ~9.2e18) is ignored, so per_days falls back to .always and ttl_days to a permanent dismissal.

Seen/dismiss memory (.once, .perDays, ttlDays) is stored per item id in _optima_seen (SeenMemory); the .session rule additionally keeps an in-memory set that's cheaper to check and doesn't need to survive a restart. A fresh fetch that genuinely changes a slot's contents (not a 304 Not Modified) resets that slot's impression dedup memory specifically — so an .always-frequency item served again after a real content change reports a new impression, rather than being silently deduped forever against a Presentation instance that no longer exists. Dismiss/shown-once memory is untouched by this — only the impression-reporting dedup resets.

Campaign mobile_inapp items and feedback

An onsite-campaign item (origin == "campaign", isCampaign == true) is a per-profile content entitlement the campaign engine created for this specific device — served once, feedback-tracked precisely:

  • Impression: reported once an item has been on screen for at least 50% visible for 1 second — optimaImpression(minVisible:dwell:_:) (chapter 3) measures this for you on every built-in renderer (BannerView, InAppView); if you're rendering headlessly, you own this timing check yourself before calling content.report(presentation, action: .impression).
  • Click: content.report(presentation, action: .click), fired by the built-in renderers' CTA button. If the item's campaign display carries stopOnClick == true, the item is also immediately removed from its slot's presentations — a "one click and it's gone" surface.
  • Dismiss: content.report(presentation, action: .dismiss), which also removes it from the slot and starts its ttlDays suppression clock.

maxImpressions (part of CampaignDisplay) is enforced server-side, not locally — the SDK reports every impression it sees; the campaign engine, not the device, is the source of truth for "this entitlement has been shown enough times," and stops serving the item once its budget is spent. The device-local campaignDisplay fields you do see (dismissible, stopOnClick) are the ones the SDK itself needs to act on immediately without a round trip.

Custom renderers

For your own structured content types, implement OptimaRenderer and register it — typically once, right after Optima.initialize:

struct ProductCarouselRenderer: OptimaRenderer {
    func render(_ presentation: Presentation, actions: RenderActions) -> some View {
        let skus = Json.arr(presentation.item.payload?["skus"]) ?? []
        return ProductCarousel(skus: skus, onTap: { sku in
            actions.onClick()
            actions.openURL(URL(string: "app://com.example.shop/Product/\(sku)")!)
        })
        .onAppear { actions.onImpression() }
    }
}
Optima.shared.content.register(type: "product_carousel", ProductCarouselRenderer())

Once registered, both OptimaHost and OptimaSlot pick it up automatically via content.rendererFor(type:) — you never call it directly. A registered renderer takes precedence over every built-in structured type, so an app can replace mobile_inapp or banner with its own view by registering under that same type name. An unregistered structured type surfaces as a plain .contentItem event instead (see chapter 3), so registering nothing for a type you don't care about is a safe default, not a broken one.

Headless use

Skip OptimaSDKUI entirely and drive content yourself with content.fetch(slot:) (one-shot, no rules applied — you own targeting, frequency, and placement) or content.slot(name) (declared, rules applied, still no rendering) plus manual content.report(...) calls for whatever you display. This is the right choice for a UIKit-only app that isn't adopting SwiftUI, a game engine surface, or any UI that the built-in renderers' styling wouldn't fit anyway. content.report takes a Presentation (not a bare ContentItem) precisely so a headless caller has already gone through content.slot/the rule engine and carries the placement/dismissible context the reporter needs — construct one from a fetched ContentItem only if you're also reimplementing the display-rule logic yourself; the ordinary path is always through a declared slot.

Unstructured HTML

Operator-authored raw HTML/CSS/JS items (format == "unstructured", the Web SDK's unstructured items) render in an isolated WKWebView when display.htmlMode = .webView (the default, HtmlView.swift) — a non-persistent WKWebsiteDataStore (no cookies or storage shared with the rest of the app, or with any other WKWebView your app owns), JavaScript enabled, scrolling disabled.

Auto-height. The view starts 1pt tall and transparent. An injected bootstrap script (HtmlItemMessage.bootstrapScript, a WKUserScript at document end) measures the content as ceil(body.getBoundingClientRect().height + body margin-top + margin-bottom) and posts it to the native side; the view takes that height and only then becomes visible. Later size changes (images, fonts, rotation) are observed with a ResizeObserver on document.body (falling back to load/resize) and update the height. When that measure is ≤ 1pt (typically an authored html, body { height: 100% }, which resolves against the view's own 1pt height) it falls back to document.documentElement.scrollHeight. When the page finishes loading the SDK measures once more with evaluateJavaScript and makes the view visible regardless, so an item is never left invisible.

Declarative actions — no JavaScript needed. Two attributes, on the clicked element or any ancestor (the nearest match wins):

<button data-actiontype="close">×</button>
<a data-link="https://example.com/sale">Shop the sale</a>
<div data-actiontype="deeplink" data-link="myapp://offers/42">Open offer</div>
  • data-actiontype="close" dismisses the item through the normal dismiss path (content.report(_, action: .dismiss)): a campaign item reports dismiss, the item's dismiss memory is recorded (ttl_days) and the presentation is removed from its slot/host. It takes precedence when both attributes sit on the same element.
  • data-link="<url>" (optionally with data-actiontype="browser" or "deeplink", treated identically) reports a .click and hands the URL to RenderActions.openURL, exactly like a plain link below. A value that isn't an absolute URL, or whose scheme the link policy refuses, is ignored.

Either way the click is cancelled inside the page (no in-place navigation). The bridge is a WKScriptMessageHandler named optima, registered through a weak proxy and removed when SwiftUI dismantles the view.

The item cannot leave its own document. Every main-frame navigation other than the initial about:blank load is cancelled (WKNavigationDelegate.decidePolicyFor): a window.location = …, a meta refresh or a form post simply does nothing. A user-tapped link (including a target="_blank" one) is instead reported as a .click and handed to RenderActions.openURL, if the link policy below allows it. openURL sends http/https to SFSafariViewController and anything else through UIApplication.open. Iframes inside the item load normally inside their own box, but only the item's own document can send close/link messages.

HtmlLinkPolicy decides which links an HTML item may open: http/https URLs with a host always; the URL schemes your app registers in Info.plist (CFBundleURLTypes, i.e. your own deep links) always; any other scheme — tel:, sms:, mailto:, another app's scheme — only when listed in display.htmlUrlSchemes (e.g. ["tel", "mailto"], case-insensitive). Everything else is ignored silently. Structured items' cta_url is not affected by this policy.

Two more behaviours specific to the HTML renderer:

  • Its impression follows the same rule as the structured renderers — at least 50 % visible for 1 s — counted only once the item has become visible (its first height report). An item that loads off-screen or below the fold reports nothing until it is scrolled into view.
  • Script-driven new windows are not implemented. HtmlView sets no WKUIDelegate, so the webView(_:createWebViewWith:…) request WebKit raises for window.open(...) is dropped silently — no navigation, no .click, no error. A target="_blank" link tap is handled like any other link (above). Author HTML items with plain links.

Set display.htmlMode = .off to disable this renderer entirely. An unstructured item then never becomes a Presentation: it is emitted as a .contentItem(slot, item) event so you can render (or ignore) it yourself. There is no "render it, but without JS" middle setting. Because it never becomes a Presentation, an .off item also bypasses the SDK's frequency/dismiss memory (display rules, _optima_seen) — same as an unregistered structured type — so it is on your own code to avoid re-showing it if that matters for your UI.

HTML in-app messages

An Optima Campaign mobile_inapp template authored in HTML (rather than the built-in title/body/image/CTA form) reaches the SDK as an ordinary campaign content item with format == "unstructured" — everything in Unstructured HTML above applies, plus a native frame OptimaHost draws around it.

Overlay vs inline follows the item's display.placement exactly as for any other item (Slots and placement): an overlay message needs nothing beyond the app-root OptimaHost() every app already has; an inline message needs an OptimaSlot("<slot>") matching the template's configured slot name, the same as a structured inline item.

The three frames

OptimaHost picks a frame from display.style/display.position (overlayFrame(rule), OptimaSDK) and draws it around the item's WebView — the HTML itself stays transparent and draws the visible card; the frame only positions it:

styleGeometry
card (default)16pt inset on all sides, 16pt corner radius, max width 420pt, at position top / center / bottom (default bottom).
barEdge to edge, no radius, pinned to top or bottom only — center falls back to bottom.
modalAlways centred over a 40%-opacity black backdrop, max width 420pt; tapping the backdrop dismisses the item when it's dismissible.

An unrecognised style value is treated as card. This is independent of InAppView's own style handling for structured mobile_inapp items (display rules) — that renderer draws its own dialog chrome; the frame described here only applies to format == "unstructured" items.

The native close button

A dismissible item whose HTML contains no data-actiontype="close" element of its own gets a small native ✕ drawn in the frame's top-right corner (needsNativeClose, a simple case-insensitive check for that attribute in the item's HTML). Every close path — the native ✕, a backdrop tap on a modal, or the HTML's own data-actiontype="close" element — reports the same dismiss action. Recommendation: include your own data-actiontype="close" element styled to match the message (see Declarative actions above) so you control its look and position instead of getting the generic native one, and set html, body { background: transparent; } in the item's CSS so only your card's own background paints — the frame itself draws nothing but position.

display.htmlMode = .off applies here exactly as it does for any other unstructured item: the message never becomes a Presentation (so it never gets a frame either) and is instead emitted as a .contentItem event.

web_personalization

Items of type web_personalization (server-side rendered template personalization, a purely web concept — it depends on rewriting DOM content that doesn't exist on a native screen) are dropped, silently as far as your app's UI is concerned, with a single debug-level log line the first time it happens per process ("web_personalization items are not applicable on iOS; dropped"). They are excluded from .contentLoaded's count. If you're targeting the same slot from both web and mobile, expect web_personalization items to simply never reach an iOS device — there is nothing to configure to change this, and nothing about the SDK is broken if you never see one come through.

On this page