Skip to content
Optima docs
SDKsiOS SDK

Consent

iOS SDK v1.4.0 — Consent

The store

Consent lives in one ConsentState, persisted to UserDefaults under the key _optima_consent and mirrored in memory, delivered via observe(_:)/ changes: AsyncStream<ConsentState> (Internal/ConsentStore.swift). It survives process death and app restarts; it does not survive reset() (see chapter 3), because a reset means a different person is now using the device, and their consent is not the previous person's to inherit.

public struct ConsentState: Equatable {
    public var v: Int = 1
    public var decisions: [String: Bool] = [:]
    public var decidedAt: Int64? = nil
    public var bannerId: String? = nil
    public var policy: [String: String]? = nil
    public var lang: String? = nil
    public var decided: Bool { decidedAt != nil }
    public var granted: [String] { decisions.filter { $0.value }.keys.sorted() }
}

decided is the load-bearing question: it's what beforeDecision = .buffer gates on, and what the purposes declaration below keys off of. granted is the sorted list of purposes currently true.

beforeDecision semantics

  • .buffer (the default): every hit built before a decision exists still queues into the on-disk outbox, but the tracker's flush loop refuses to send while !consent.get().decided — hits pile up locally instead of leaving the device. The moment the first consent.set(...) call completes its local write, the queue is unblocked (Tracker.scheduleFlush(), called from ConsentFacade.set) and everything queued so far ships in the next batch(es), each carrying the now-decided consent declaration.
  • .send: hits flush on the normal batch/coalesce schedule regardless of whether a decision exists yet. This is correct when your own consent UI gates calling Optima.initialize at all (you don't initialize until consent is known), or under source = .cmp (forced automatically — see chapter 2), where the CMP owns the decision and there's nothing of ours to buffer for.

Buffered hits are not exempt from the 200-entry outbox cap (OutboxCap) — a very long undecided period on a very active app can still lose the oldest hits, same as any other backlog.

Buffered hits expire after 30 minutes (Tracker.bufferMaxAgeMs, the Web SDK's value). A hit collected while no decision existed is sent only if the decision arrives within 30 minutes of that hit; older ones are dropped unsent (logged as a warning). Hits collected after a decision never expire, however long they wait for connectivity.

Delivery of the decision itself

consent.set writes the decision locally first, then stores the /edge/v1/consent request in a durable queue (_optima_consent_pending) before posting it. A request the edge accepts, or rejects with a 4xx, leaves the queue; one that runs out of retries (offline, 5xx) stays and is replayed at the next launch and on every foreground, oldest first, until the edge answers. The Task consent.set returns resolves after the first attempt. Queued requests keep the device id they were made under, so a decision taken just before reset() still reaches the server for the device it belongs to.

The omit-vs-[] declaration rule

This is the single most important consent detail in the whole SDK, and it's identical to the Web and Android SDKs' rule (ConsentStore.declaration()):

if source == .optima && s.decided { out["purposes"] = s.granted }
  • No decision yet (!decided): the purposes key is omitted entirely from the request's consent block (in fact, if nothing else — no TCF string, no GCM map, no keys — is set either, declaration() returns nil and the whole consent key is omitted from the request body). Omission means "consent is unknown," and the server treats an unknown purpose per its own configured default (which, depending on the purpose's collection-gate configuration, ranges from "allow" to "quarantine until known" — that policy lives entirely server-side and the SDK has no opinion on it).
  • A decision exists, everything rejected: purposes is sent as an explicit empty array []. This is not the same thing as omission — [] means "we asked, and the answer was no to everything," a materially different fact than "we haven't asked." Never conflate these two states in your own code if you ever touch ConsentState directly; the built-in banner and consent.set(...) already get this right, this note exists so a custom consent UI built against consent.set doesn't accidentally collapse them.

source = .cmp never declares purposes at all, decided or not — see below.

The built-in banner

When consent.source = .optima (the default) and the content engine's fetch for the implicit overlay slot (or any declared slot) returns a banner_consent-type item, OptimaSDKUI's OptimaHost renders it automatically via ConsentBannerView — you don't need to write any banner UI yourself. It's a two-stage surface:

  1. Summary: title + body copy, and three actions — Accept all, Reject all, Manage.
  2. Manage (reached via the third button): a per-purpose Toggle row for every purpose in the item's purpose_details payload, seeded from the current decision (or false if undecided), plus a Save button.

Copy is resolved per language from the item's payload.languages map (Copy.banner), with a fallback ladder: your consent's currently-stored lang → the device's full preferred-language tag → the device's primary language subtag → "en" → whatever language key happens to exist first. Each of Accept all, Reject all, and Save calls consent.set(decisions, meta: ConsentMeta(bannerId: item.id, lang: resolvedLang)) — there's no separate "dismiss" call for a consent decision; posting the decision is what makes the banner go away.

Two details of the sequencing matter if you're writing your own banner:

  • Server-side suppression is eventually consistent. The gateway stops serving the banner_consent item once the decision has landed and been processed, which is not the same instant the POST returns. So ConsentBannerView removes the banner locally first (content.report(presentation, action: .dismiss) — a banner_consent item carries no feedback token, so this posts nothing to the server; it only drops the presentation from its slot), and only then awaits the consent.set task and calls content.refresh(). Refreshing without waiting for the POST races it, and the banner comes straight back.
  • The built-in banner does not populate ConsentMeta.policy. It sends bannerId and lang only. (The Android SDK passes the item's payload.policy through here; iOS does not yet — tracked in the SDK repository's TODO file.) A custom UI that needs policy-version round-tripping can read it out of the item payload and pass it itself.

If you're writing your own consent UI instead of using the built-in one (perhaps because your design system doesn't fit ConsentBannerView), the recipe is: fetch the banner_consent item yourself (headless — chapter 5), render your own screen from its payload.languages/payload.purpose_details (Copy.banner/Copy.purposes are public and reusable for this), and call consent.set(...) with the same shape. ConsentMeta.policy exists precisely so a custom UI can still round-trip the policy-version metadata the server expects, without needing to understand its internal shape.

CMP passthrough

Two independent knobs, both covered from the config side in chapter 2:

  • TCF: read automatically, always, regardless of source — TcfSource (TcfDefaults on Darwin) reads IABTCF_TCString from UserDefaults.standard (the location every IAB-compliant CMP SDK writes it to) and observes it for changes. You never need to call consent.setTCF yourself unless you're deliberately overriding what a CMP wrote, or testing without a real CMP installed.
  • GCM / arbitrary keys: manual only — there is no Google Consent Mode dataLayer equivalent to read natively on iOS (that's a web-page concept). Call consent.setGCM(["ad_storage": .denied, ...]) / consent.setKeys([...]) yourself, typically from your CMP SDK's own consent-changed callback.

source = .cmp additionally stops the SDK from declaring its own purposes array at all (see the omit-vs-[] section above — under .cmp that whole branch of declaration() is skipped regardless of ConsentState.decided), and diverts any served banner_consent item away from ConsentBannerView into a plain .contentItem event for you to route into your CMP's own UI flow instead — see chapter 3.

Gating third-party SDKs

consent.can(trackerName) plus consent.changes is the pattern for deciding, at runtime, whether a third-party SDK you initialize yourself is allowed to run — the SDK doesn't (and can't) reach into another vendor's SDK and stop it, but it can tell you the answer so your own init code can decide. A typical Firebase Analytics gate, re-checked on every consent change:

final class AnalyticsGate {
    private var initialized = false
    private var sub: OptimaSubscription?
    func start() {
        sub = Optima.shared.consent.observe { [weak self] _ in
            guard let self else { return }
            let allowed = Optima.shared.consent.can("firebase_analytics")
            if allowed && !self.initialized {
                Analytics.setAnalyticsCollectionEnabled(true)
                self.initialized = true
            } else if !allowed && self.initialized {
                Analytics.setAnalyticsCollectionEnabled(false)
                // Firebase keeps running once initialized; disabling collection is the
                // available lever — a true "unload" isn't offered by that SDK either.
            }
        }
    }
}

"firebase_analytics" here must be a name registered in the Optima console's tracker inventory (edge_trackers, the same table the SDK reads via GET /edge/v1/trackers, fetched once per process and cached — see chapter 8), with its purpose pointed at whichever consent purpose should gate it. consent.can returns false (fail-closed) for any name that isn't in that inventory or hasn't loaded yet — a typo in the name you pass silently gates the SDK off forever, so double-check it against the console.

Revocation

.consentRevoked(purposes:) fires whenever a consent.set(...) call flips a previously-true purpose to false. A running third-party SDK cannot be unloaded — there is no public iOS API to un-initialize an already- initialized library's runtime, background threads, or file handles it opened. The event is your signal to do whatever your SDK's own "stop/ disable" API offers (as in the Firebase example above), and the app is the one that decides what "stop" means for each vendor it embeds — the platform SDK itself has no opinion on what compliance requires you to do in response.

reset() on logout

reset() clears _optima_consent back to a fresh ConsentState() (undecided, no purposes) as one of its first steps, and emits .consentChange with that fresh state. On a shared/kiosk device, call it on every logout — the next person who picks up the device should see the consent banner again, not inherit the previous person's decision. See chapter 3 for the full ordering of what else reset() clears.

App Tracking Transparency

ATT is the app's concern, not the SDK's. Optima.initialize/track/ identify never touch AppTrackingTransparency, never read ASIdentifierManager.advertisingIdentifier, and the device identifier the SDK mints (deviceId) is a UUID of its own, unrelated to IDFA. If your app wants to use IDFA for its own attribution or ad-platform integrations, that remains your own ATTrackingManager.requestTrackingAuthorization call and your own decision about what to do with the result — nothing about wiring that consent into Optima differs from wiring in any other consent signal: call consent.setKeys(["idfa_tracking": granted]) (or whatever purpose name your console configuration uses) from your ATT authorization callback the same way the Firebase example above reacts to consent.changes.

On this page