Forms
iOS SDK v1.4.0 — Forms
This iteration ships headless form loading and submission —
forms.load/the bound submit closure — plus a link into the hosted,
server-rendered form page for cases where a fully native form isn't worth
building yet. There is no native form-rendering View shipped in
OptimaSDKUI (no OptimaForm(id) that draws inputs for you); see
chapter 8 for why that differs from the Web SDK's
forms.render.
Loading and submitting a form
let result = await Optima.shared.forms.load(id: "newsletter-signup")forms.load(id:lang:) (or forms.load(id:lang:assertion:) for a logged-in visitor, see chapter 3) returns a FormResult:
.loaded(definition, submit:)— the happy path.definition: FormDefinitioncarriesfields: [FormField](each withkey,kind,inputType,label,placeholder,required,optionsfor select/radio-style fields), plussuccessMessage,successRedirectUrl,doubleOptIn, andminSubmitIntervalSec.submitis a bound closure —([String: Any]) async -> SubmitResult— that already carries the form's render nonce internally; you never see or handle the nonce yourself..notFound— the form id doesn't exist or isn't published..failed(status:cause:)— a network failure or an unexpected status.
A minimal SwiftUI form built from a loaded definition:
struct NewsletterForm: View {
let formId = "newsletter-signup"
@State private var result: FormResult?
@State private var values: [String: Any] = [:]
@State private var outcome: SubmitResult?
var body: some View {
Group {
switch result {
case .loaded(let def, let submit):
VStack {
ForEach(def.fields, id: \.key) { field in
TextField(field.label + (field.required ? " *" : ""), text: Binding(
get: { (values[field.key] as? String) ?? "" },
set: { values[field.key] = $0 }))
}
Button("Submit") { Task { outcome = await submit(values) } }
switch outcome {
case .accepted: Text(def.successMessage ?? "Thanks!")
case .rejected: Text("Please check your entries.")
case .failed: Text("Something went wrong — try again.")
case nil: EmptyView()
}
}
case .notFound: Text("This form is no longer available.")
case .failed: Text("Couldn't load the form — check your connection.")
case nil: ProgressView()
}
}
.task { result = await Optima.shared.forms.load(id: formId) }
}
}submit's value map accepts String, Bool, integers, and finite
Double/Float. An NSNull value (an explicit "no value" for a key) is
dropped silently, no log — that's the normal shape of an unanswered optional
field. Anything else unsupported (an array, a nested object) is also
dropped, but with a debug log naming the field, since that shape usually
means a bug in how your UI built the values map rather than an intentionally
empty field — either way it costs you that one field, not the customer's
whole submission.
The honeypot and the nonce, handled for you
Every submission includes an empty honeypot field (_hp) and the render
nonce the form definition carried privately — both anti-bot measures the
hosted form page also uses, and both are wired up inside submit(...)
without any action on your part. You cannot see or tamper with either from
the public API, by design: there is nothing to configure and nothing that
can be gotten wrong here.
409 means "already submitted"
If the device has already submitted this form (the server enforces
min_submit_interval_sec and/or a one-submission-per-device rule
server-side), the submit endpoint answers 409, and the SDK treats that as
a success, not an error: .accepted(dropped: [], doubleOptIn: definition.doubleOptIn), and a .formSubmitted event fires the same as a
genuine first-time acceptance. Don't special-case 409 in your own UI — by
the time it reaches SubmitResult, it's already been normalized into the
same "it worked" shape as a real 200.
Double opt-in
When definition.doubleOptIn is true (or the server's response to a
submission says so — the doubleOptIn in .accepted reflects whatever the
server actually decided, which can differ from the definition's declared
default in edge cases), the profile's consent for whatever the form grants is
not yet active — a confirmation email/link has to be completed first.
There's nothing further for the SDK to do here: the confirmation flow itself
runs entirely server-side (GET/POST /edge/v1/forms/confirm/:token,
addressed by a link in an email, deliberately outside any mobile deep link —
the design spec's rationale is that a GET must never mutate, so a
mail-scanner can't manufacture consent). Surface doubleOptIn == true in
your own UI as "check your email to confirm" copy, if your form's purpose
warrants it.
Hosted pages
For a form you don't want to build a native screen for yet — a long
multi-section form, or one that changes frequently and you'd rather not ship
an app update for — open the operator's hosted, server-rendered page in
SFSafariViewController instead:
let url = Optima.shared.forms.pageURL(URL(string: "https://edge.shop.example/edge/v1/pages/<sdk-key-token>/newsletter-signup")!)
present(SFSafariViewController(url: url), animated: true)OptimaSDKUI's own SafariView (the one BannerView/InAppView/
ConsentBannerView use for outbound links) is internal, not part of the
public API — you can't reference it from app code. Wrap
SFSafariViewController in your own UIViewControllerRepresentable the same
way, if you want a SwiftUI-native equivalent instead of present(...)
above; it's six lines:
struct SafariView: UIViewControllerRepresentable {
let url: URL
func makeUIViewController(context: Context) -> SFSafariViewController { SFSafariViewController(url: url) }
func updateUIViewController(_ vc: SFSafariViewController, context: Context) {}
}forms.pageURL(url) appends device_id=<id> as a query parameter (creating
the ? if the URL doesn't already have one) — this is what lets the hosted
page's own submission attribute back to the same device identity the rest of
the SDK uses, so a form filled out in SFSafariViewController and an
identify(...) call made natively both resolve to the same profile. The
hosted page URL itself (/edge/v1/pages/:token/:slug) is addressed by
SDK-key token rather than by X-Edge-Key header, because a browser
navigation — which SFSafariViewController is — can't send a custom header;
get the exact URL for a given form from the Optima console's forms admin
screen.