Widget guides / iOS
Chat widget in your iOS app: Swift and SwiftUI
Add one Swift file to your app and visitors get a chat that answers questions about matches, teams and players, with stats and your prices. This guide covers every setting, callback and object the file gives you.
Checklist:
- Get your operator id, public key, widget origin and the wrapper file from your SensibleStats contact.
- Ask your contact to switch mobile on for your account.
- Add the file, create one
SensibleStatsChatwith the signed-in visitor's id, and show the sheet. - Set
onAddToSlip, then test an add, a duplicate and a reject. - Set
onUnavailable, and reload the chat when the visitor signs in or out.
1. What your visitors get#
- A chat icon in a bottom corner, with a teaser beside it: a short greeting about a game, often with one of your prices and a few suggested questions.
- A chat sheet where visitors ask in their own words and get answers as text and cards: stats, form, line-ups, standings and your prices.
- Add to slip. A price in the chat carries a button that hands the selection to your code (section 7).
Terms used in this guide:
- Wrapper is
SensibleStatsChat.swift, the file your SensibleStats contact sends you. It shows our chat pagehttps://your-widget-host/min aWKWebViewand passes messages between that page and your code. You never build the page URL yourself. - Operator id and public key identify your account to our server.
- Widget origin is the address of our server for your account, shown here as
https://your-widget-host. - Teaser is the short greeting bubble next to the chat icon.
- Bet slip (or slip) is the list of selections a visitor collects in your app before placing a bet.
- Price is your odds for one selection.
matchOddsIdis your sportsbook's own id for one selection: one outcome of one market.operatorUserIdis your id for the signed-in visitor (section 5).
2. Before you start#
You need three values and the wrapper file from your SensibleStats contact.
| From us | Example | What it is |
|---|---|---|
| Operator id | YOUR_OPERATOR_ID | Your account in our system. Part of every request. |
| Public key | YOUR_PUBLIC_KEY | Identifies your widget. |
| Widget origin | https://your-widget-host | The address the chat page is served from. Must be https. |
| Wrapper | SensibleStatsChat. | The file you add to your app. |
| To us | Why |
|---|---|
| Ask your contact to switch mobile on for your account | Until then the chat does not start and reports mobile_disabled (section 11). There is no list of allowed domains for mobile. |
What your app needs:
| Requirement | Value |
|---|---|
| iOS | 16.4 or later |
| Swift | Swift 5.7 or later compiler (the file is written in Swift 5 language mode) |
| Frameworks | SwiftUI, UIKit, WebKit (all part of iOS) |
| A signed-in visitor | Required. With no visitor id the chat does not start (section 5). |
3. Add the widget#
Add SensibleStatsChat.swift to your app target. Its types have no public modifier, so put it in
the app target itself, not in a separate module. Code inside #if SS_TEST_HOOKS is for our tests and
is not compiled in your app.
SensibleStatsChat.wrapperVersion holds the file's version, "1.0.0" today. Quote this value when
you contact us; your contact tells you when to update.
Create one SensibleStatsChat and keep it alive for the life of the app, for example as a
@StateObject on your App:
import SwiftUI
func makeChatConfig(userId: String) -> SensibleStatsConfig {
SensibleStatsConfig(
baseUrl: URL(string: "https://your-widget-host")!,
operatorId: "YOUR_OPERATOR_ID",
publicKey: "YOUR_PUBLIC_KEY",
userContext: .init(operatorUserId: userId),
locale: "en-GB",
greetingMessage: "hello"
)
}
@main
struct MyApp: App {
@StateObject private var chat = SensibleStatsChat(config: makeChatConfig(userId: currentUser.id))
var body: some Scene {
WindowGroup {
ContentView(chat: chat)
}
}
}Names that start with my, My or Your, and currentUser, stand for your own code.
Creating SensibleStatsChat starts loading the chat page in the background, so the teaser can
arrive before the visitor opens anything.
Then place the icon and the sheet on your screen. The wrapper gives you the icon
(SensibleStatsLauncher). The sheet is a small view in your app:
import SwiftUI
import WebKit
struct ContentView: View {
@ObservedObject var chat: SensibleStatsChat
var body: some View {
YourScreen()
.overlay { SensibleStatsLauncher(chat: chat) }
.sheet(isPresented: $chat.isOpen) {
ChatSheet(webView: chat.webView)
.ignoresSafeArea(.container, edges: .bottom)
.presentationDetents([.large])
}
.onAppear {
chat.onAddToSlip = { selection in
await mySlip.add(selection)
}
}
}
}
struct ChatSheet: UIViewRepresentable {
let webView: WKWebView
func makeUIView(context: Context) -> WKWebView {
webView.scrollView.keyboardDismissMode = .interactive
webView.scrollView.contentInsetAdjustmentBehavior = .never
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {}
}Here mySlip.add returns a SensibleStatsChat.SlipResult? (section 7). There is one webView per
SensibleStatsChat; show it in one place at a time.
chat.isOpen drives the sheet. The icon, the teaser and open() set it; close(), a swipe down,
the chat's own close button and an unavailable chat (section 11) clear it.
4. Settings#
SensibleStatsConfig is a struct. Every field except the first four has a default. The wrapper's
own types are nested: SensibleStatsChat.PageContext, SensibleStatsConfig.Theme and so on. Where
Swift knows the type, write .init(...) or a case such as .dark.
Required#
| Field | Type | What it does |
|---|---|---|
baseUrl | URL | The widget origin, https://your-widget-host. Must be https with a host; its path, query and fragment are ignored. A URL without a host stops the app with baseUrl needs a host. Over http the page loads but the chat never becomes available. |
operatorId | String | Your operator id. |
publicKey | String | Your public key. Empty operatorId or publicKey gives auth_failed. |
userContext | SensibleStatsConfig. | .init(, the signed-in visitor. See section 5. |
Visitor, language and time#
| Field | Type | Default | What it does |
|---|---|---|---|
locale | String? | your account's default language (English unless you asked for another) | The language of the chat and its answers, e.g. en-GB, tr. |
timeZone | String? | the device's zone | IANA zone, e.g. Europe/. Kick-off times and day names follow it. |
oddsFormat | SensibleStatsChat. | nil (decimal) | .decimal, .american or .fractional. How prices are written. A visitor who picks a format in the chat's settings keeps their choice. |
Greeting and page#
| Field | Type | Default | What it does |
|---|---|---|---|
greetingMessage | String? | nil | Sent once when the page loads; the answer becomes the teaser. Use "hello". Without it there is no greeting and no teaser. |
page | SensibleStatsChat. | nil | The screen the visitor is on, so the greeting can lead with it. Section 6. |
placeholder | String? | localized | Text in the empty question box. |
starters | [String]? | nil | Suggested questions shown in an empty chat. |
Look#
| Field | Type | Default | What it does |
|---|---|---|---|
theme | SensibleStatsConfig. | .auto | .light, .dark or .auto. .auto follows the device's appearance. A visitor who picks a theme in the chat keeps their choice, and the icon follows it. |
colors | SensibleStatsConfig. | nil | .init(, each a ThemeColors?. Section 10. |
logoUrl | String? | our mark | Your square logo, shown on the icon and in the chat header. The icon loads only https: and data: URLs. |
headerTitle | String? | SensibleStats | The chat's title. |
position | SensibleStatsConfig. | .right | .left or .right: which bottom corner the icon sits in. |
offset | SensibleStatsConfig. | .init( | Distance in points from the side and from the bottom of the view the icon overlays. |
radius | Double? | 16 | Corner radius of the chat panel, in points. Negative or non-finite values are dropped. |
launcher | Bool | true | false hides our icon and teaser so you draw your own (section 8). |
launcherLabel | String? | "Chat with SensibleStats", localized | The icon's label for VoiceOver. Until the page answers, the icon's label is English "Open chat"; to change that, set the sensiblestats. string in your Localizable.. |
pinIcon | SensibleStatsConfig. | .pin | .pin, .star or .bookmark: the icon visitors tap to follow a match or price. |
Slip, callbacks and events#
| Field | Type | Default | What it does |
|---|---|---|---|
slipSports | [SensibleStatsChat. | nil | .basketball, .americanfootball, .tennis: the sports your onAddToSlip accepts besides football. Section 7. |
eventText | Bool | false | Adds the visitor's question text to question_asked events. Answer text is never sent. |
Callbacks are not config fields. They are properties of SensibleStatsChat, called on the main actor:
| Property | Swift type | What it does |
|---|---|---|
onAddToSlip | ( | Adds a price to your bet slip. Section 7. |
onTeaser | ( | Gives you the teaser to draw yourself. Section 8. |
onUnavailable | ( | Tells you the chat cannot start. Section 11. |
onEvent | ( | Every widget event, for your own analytics. Section 9. |
5. The signed-in visitor#
Pass your id for the signed-in visitor in userContext.operatorUserId. Use a random, non-guessable
id that never changes for that account and that you map to the customer on your side (a UUID works).
Never use a customer number, email address or name: the id comes from the visitor's device, and
anyone who knows it can act as that visitor.
The id is required. If it is empty or only spaces, the chat does not start and reports no_user
(section 11).
With the id, the visitor's chat, followed matches and favourites belong to their account, and the greeting can lead with the teams and markets they bet on.
When the visitor signs in or switches account, reload with a new config:
chat.reload(config: makeChatConfig(userId: newUserId))When the visitor signs out, reload with an empty id. The chat closes, the icon hides and
onUnavailable(.noUser) is called:
chat.reload(config: makeChatConfig(userId: ""))reload(config:) keeps the same SensibleStatsChat and webView and loads the page again. It
clears the teaser, drops calls not yet delivered, ends a pending tapPrice() with nil, and reopens
the chat if it was open. baseUrl must stay the same origin; a different one stops the app with
baseUrl cannot change on reload. For another origin, create a new SensibleStatsChat.
Use reload(config:) for any other config change too, such as language or colours.
6. The page the visitor is on#
Tell the chat which screen it sits on and the greeting leads with that game, competition or sport.
Set page in the config, or call chat.setPage(_:) when the visitor moves to another screen, and
chat.setPage(nil) on a screen that is about no sport.
chat.setPage(.init(sport: .football, kind: .match, matchId: .number(19432556)))setPage only tells the page that is loaded now. After reload(config:) the chat starts from
config.page, so put the current screen in the config you reload with.
SensibleStatsChat.PageContext:
| Field | Type | Default | Meaning |
|---|---|---|---|
sport | SensibleStatsChat. | required | .football, .basketball, .americanfootball, .tennis. |
kind | SensibleStatsChat. | nil | .section, .competition or .match: a sport's front page, a competition page, or a match page. |
matchId | SensibleStatsChat. | nil | Your sportsbook's id for the match on a match page. |
competitionId | SensibleStatsChat. | nil | Your sportsbook's id for the competition on a competition page. |
PageId is .number(Int) or .text(String), so you can pass your id in whichever form you hold it.
7. Add to slip#
The chat shows your prices, each with an "Add to slip" button. This is how a tap reaches your slip:
- The visitor taps "Add to slip" under a price.
- The wrapper calls
onAddToSlip(selection).selection.matchOddsIdis your sportsbook's own id for that selection, so you can look it up directly. - Your code adds that selection to your slip and returns a
SlipResult. - The chat shows the visitor a short note in their language, such as "Added to slip".
chat.onAddToSlip = { selection in
guard mySlip.contains(selection.matchOddsId) == false else { return .duplicate }
mySlip.add(selection.matchOddsId)
return .added()
}The handler is async, so you can await your own slip service. It runs on the main actor.
You have 10 seconds to answer. No answer in time counts as a failure: the visitor sees "Couldn't add to slip. Try again." We don't cancel your handler at 10 seconds, so give your slip call its own timeout under 10 seconds, and don't add the selection after it fires.
The button is always shown on mobile. Until you set onAddToSlip, the wrapper answers every tap
with .rejected(reason: .unsupported), so set it before the visitor can open the chat.
What the wrapper gives you: SensibleStatsChat.Selection
| Field | Type | Meaning |
|---|---|---|
matchOddsId | Int | Your sportsbook's id for the selection. Look it up in your slip. |
matchId | Int | Your sportsbook's id for the match. |
oddsDecimal | Double | The price the visitor saw, as a decimal. |
sport | SensibleStatsChat. | nil (or .football) means football. .basketball, .americanfootball or .tennis otherwise. |
tour | String? | Tennis only: the tour the match id belongs to. |
odds | SlipOdds? | The same price in your account's odds format (not the visitor's own choice): format (e.g. "american") and text (e.g. "+150"). |
quotedAtUtc | String? | ISO time when that price was last confirmed. |
conversationId, insightId | String? | Which chat and which card the tap came from. |
display | SlipDisplay? | The pick in words, for showing only: home, away, kickoffUtc, market, marketLabel, selection, line, player, each a String?. Never price or settle a bet from these. |
Every field after tour is optional: one the page leaves out or sends with the wrong type is nil
and never stops the selection reaching you. A selection that lacks matchOddsId, matchId or
oddsDecimal never reaches your handler; the wrapper answers unsupported for you.
What you return: SensibleStatsChat.SlipResult
| Return | When | The visitor sees (English) |
|---|---|---|
.added() or nil | The selection is in the slip. .added( also takes a SlipSummary(; it is accepted but not shown today. | Added to slip |
.duplicate | It was already in the slip. | Already in your slip |
.priceChanged( | The price moved and you added it at the new price. newOdds is the new price as text. | Added at 2.10 (was 1.95) |
.priceChanged( | The price moved and you did not add it. | Price moved to 2.10 (was 1.95). Tap to add. |
.rejected( | You did not add it. reason is a RejectReason; message is optional. | See below |
RejectReason | Meaning | The visitor sees (English) |
|---|---|---|
.loginRequired | The visitor must sign in first. | Sign in to add to your slip |
.suspended | The market is suspended. | Market suspended |
.closed | The market or match is closed, e.g. it has started. | Your message, else "This selection can't be added." |
.notFound, .limit, .unsupported | You don't know this selection; the slip is full or a limit is reached; you don't take this kind of selection. | Your message, else "Couldn't add to slip. Try again." |
Other languages show the same notes, translated. message is your own text, shown as is: write it
in the visitor's language. It is ignored for .loginRequired and .suspended.
Other sports. Football prices always get the button. Basketball, American football and tennis
prices get it only when slipSports lists that sport, so a handler that only knows football never
receives them:
slipSports: [.basketball, .tennis]For these sports the prices come from our own data, so matchOddsId and matchId are our ids, not
your sportsbook's. Find the selection from display (teams, kick-off, market, selection and line)
and tour for tennis, and return .rejected(reason: .notFound) when you cannot.
Telling the chat what happened next (optional). These calls help the chat track your slip. They are queued until the page is ready.
| Call | When |
|---|---|
chat. | The visitor removed a selection from your slip. |
chat. | The visitor placed a bet. Only the selections are required; a non-finite stake or totalOdds is left out. |
chat. | The visitor opened a match screen. |
SensibleStatsChat.SlipRef has matchOddsId: Int and sport: Sport? (default nil, meaning
football).
8. The icon and teaser#
By default SensibleStatsLauncher(chat:) draws the icon and teaser, in your colours, at position
and offset. It shows while chat.available is true and tells the chat when the teaser is seen.
Put the overlay on a full-screen view: the launcher fills the view it overlays and aligns to its
bottom corner.
To draw them yourself, in your app's design, set launcher: false in the config and read
chat.teaser (it is @Published), or set onTeaser:
chat.onTeaser = { teaser in
guard let teaser else { return myLauncher.hideTeaser() }
myLauncher.showTeaser(teaser.text, teaser.asks, teaser.price)
chat.teaserShown()
}onTeaser receives a Teaser when there is one, and nil when it is gone. Show your icon only
while chat.available is true.
SensibleStatsChat.Teaser:
| Field | Type | Meaning |
|---|---|---|
text | String? | The greeting line. |
asks | [Teaser. | Suggested questions, each index: Int and label: String. Show label; pass index to tapAsk(. |
cta | String? | A button label, e.g. "Build a bet". |
price | TeaserPrice? | One price: matchOddsId: Int, marketLabel (the market's name), label (the selection's name) and odds (the price as text). |
Call these when the visitor acts on your teaser:
| Call | When | What the chat does |
|---|---|---|
chat. | You showed the teaser. | Counts it as seen (once per teaser). |
chat. | The visitor tapped the teaser text. | Opens the chat. |
chat. | The visitor tapped a suggested question. | Opens the chat and asks it. |
chat. | The visitor tapped the button. | Opens the chat on it. |
await chat. | The visitor tapped the price. | Checks the price again, then calls your onAddToSlip. Returns PriceResult?. |
chat. | The visitor closed the teaser. | Clears it; onTeaser( follows. |
chat., chat. | The visitor tapped your icon, or you close the chat. | Opens or closes the sheet. |
Opening the chat clears the teaser.
While a tapPrice() is running, chat.pricePending is true; afterwards chat.priceNote holds
the note to show under the price. If you draw your own teaser, the wrapper's
SensibleStatsTeaserActions view draws the price and button part for you, in the colours from
SensibleStatsLauncherPalette.
SensibleStatsChat.PriceResult has matchOddsId: Int, outcome: PriceOutcome and text: String?
(the note to show the visitor, or nil).
outcome is .added (the selection is in the slip: added, already there, or added at a new price),
.gone (the price is no longer offered), .coolOff (too many requests; try again shortly) or .failed
(not added: your handler refused it or did not answer).
tapPrice() returns nil when there is no price, when one is already running, when the teaser is
replaced or dismissed, on reload(config:), and after 15 seconds with no result.
9. Events for your analytics#
Every visitor action is passed to onEvent as a [String: Any] dictionary, so you can forward it
to your own analytics. The chat does not check consent; gate your own sending on it.
chat.onEvent = { event in
myAnalytics.log(event["name"] as? String ?? "", event)
}Every event carries name, at (epoch ms, when it happened), operatorId and widgetVersion, and
when known language, conversationId, operatorUserId and page. A ? marks a field that can be
absent.
| Event | Fields |
|---|---|
widget_open | source? (launcher, bubble, teaser, host, popup), first? |
widget_close | method (button, escape, host for your close(), native, back), tab, answering, openMs? |
bubble_shown, bubble_click, bubble_dismiss | none |
bubble_ask_click | position |
tab_change | from, to, source? (bar, link, auto) |
question_asked | turnId, source, length, text? (only with eventText), method?, chipId?, position?, actionRef?, retryOf?, matchId? |
answer_received | turnId, conversationId, latencyMs, cardTypes, firstByteMs? |
answer_failed | turnId, code |
answer_stopped | turnId |
add_to_slip_click | matchOddsId, matchId, odds, market?, sport?, factKey?, surface?, turnId? |
add_to_slip_result | the same fields, plus outcome |
pin_click | action (add, remove), target (match, market), matchId?, market?, sport?, surface?, turnId? |
combo_add_click | surface (builder, chat), sport, legs, total, turnId? |
combo_variant_click | surface, sport, legs, total, variant |
combo_swap_click | surface, sport, legs, total |
all_markets_click | matchId, market?, surface |
dashboard_tile_click | entityType, entityId |
sport_switch | sport |
new_conversation | none |
favourite_change | kind, id, outcome, sport?, surface?, before? |
add_to_slip_result.outcome is added, duplicate, price_changed, timeout or the reject reason
you returned (login_required, suspended, closed, not_found, limit, unsupported).
timeout covers any failed add, not only a late one. odds in events is always a decimal number.
tab, from and to are one of chat, live, matches, builder, following, trends,
games, fixtures, standings, squad, records. question_asked.source is one of typed,
starter, action, tile, preset, live_fact, bubble_ask, retry, match_sheet.
10. Colours#
Each theme has four colours. A colour you leave out keeps ours. The dark theme reads only the dark colours, never the light ones. The same colours paint the chat and the native icon and teaser.
| Colour | Used for | Light default | Dark default |
|---|---|---|---|
accent | Your brand colour: links, highlights and the teaser's suggested questions. | #17936a | #37c891 |
cta | Price and "Add to slip" buttons. | #f5a623 | #ffb638 |
surface | Backgrounds: the chat, the icon and the teaser. | #ffffff | #141b24 |
ink | Text. | #14181d | #e8edf2 |
Colours are hex only: #rgb, #rrggbb or #rrggbbaa. Any other value is dropped and our colour
applies; debug builds print SensibleStats: ignoring <value>, colours are #rgb, #rrggbb or #rrggbbaa.
Set surface and ink together: the teaser, lines and faint text are then mixed from them.
colors: .init(
light: .init(accent: "#0b5fff", cta: "#ffcc00"),
dark: .init(accent: "#5c93ff", cta: "#ffd633", surface: "#0d1117", ink: "#f0f3f6")
)11. When the chat cannot start#
chat.available turns true when the page loads, and back to false if our server then refuses
the chat, so the icon can show for a moment before it hides. When the page reports one of the
reasons below, the wrapper closes the chat (isOpen is already false when your callback runs),
hides the icon, sets chat.unavailableReason and calls onUnavailable(reason). It does this every
time the page reports it, including after reload(config:). A reason this version of the wrapper
does not know only hides the icon.
UnavailableReason | Raw value | Cause | Fix |
|---|---|---|---|
.noUser | no_user | userContext. is empty, for example after sign-out. | Pass the signed-in visitor's id (section 5). |
.mobileDisabled | mobile_disabled | Mobile is not switched on for your account. | Ask your SensibleStats contact to switch mobile on for your account. |
.widgetDisabled | widget_disabled | The widget is off for your account, or the operator id is not one we know. | Check the id. If it is right, ask your contact to switch the widget on. |
.authFailed | auth_failed | The public key is wrong or empty, or the operator id is empty. | Check both values. |
Things that stop the app (Swift precondition), so you see them in development:
| Message | Cause |
|---|---|
baseUrl needs a host | baseUrl has no host. |
baseUrl cannot change on reload: create a new SensibleStatsChat for another origin | reload( was given a different origin. |
12. Platform notes#
- Links. A link to any other host opens outside your app, in the browser or the app that handles it. Frames inside the chat cannot load other hosts.
- Load failures. If the first load fails or the server answers with an error, the wrapper tries once more.
- The chat page crashes. If iOS ends the web view's content process (for example under memory pressure), the wrapper loads the page again with the same config. If the chat was open, it opens it again once ready. A second crash while the chat stays open closes the sheet instead.
- The sheet. Keep the scroll view settings in
ChatSheet, and keep.ignoresSafeArea(.container, edges: .bottom)and.presentationDetents([.large])on the sheet. - Debugging. In debug builds the web view is inspectable with Safari's Web Inspector. Release builds turn this off.
13. Reference#
SensibleStatsChat is a @MainActor ObservableObject. Create it with
SensibleStatsChat(config:).
State (read-only unless noted):
| Property | Type | Meaning |
|---|---|---|
isOpen | Bool (read and write) | Whether the chat is open. Bind your sheet to $chat.. |
available | Bool | The chat is ready (section 11). |
unavailableReason | UnavailableReason? | Why it cannot start (section 11). |
teaser | Teaser? | The current teaser (section 8). |
pricePending | Bool | A tapPrice() is running. |
priceNote | String? | The note from the last tapPrice(). |
config | SensibleStatsConfig | The config in use. |
labels | LauncherLabels? | VoiceOver labels for the icon and teaser close button, in the visitor's language. |
pageTheme | SensibleStatsConfig. | The theme the chat is showing, once it says. |
webView | WKWebView | The chat's web view, for ChatSheet. |
wrapperVersion | String, static | The wrapper's version (section 3). |
Methods:
| Method | Returns | What it does |
|---|---|---|
open(), close() | nothing | Opens or closes the chat. |
reload( | nothing | Loads the chat again with a new config (section 5). |
setPage( | nothing | Sets the page (section 6); nil clears it. |
slipRemoved(, betPlaced(, matchOpened( | nothing | Section 7. |
teaserShown(), tapTeaser(), tapAsk(, tapCta(), dismissTeaser() | nothing | Section 8. |
tapPrice() | async PriceResult? | Section 8. |
Callbacks: onAddToSlip, onTeaser, onUnavailable, onEvent (section 4). onBridgeMessage is
for our own debugging; leave it unset.