Skip to the guide

Need help? Your SensibleStats contact can answer questions about any guide and send the three values. Write to solutions@sensiblestats.com.

Highlighted values such as YOUR_PUBLIC_KEY are placeholders. Replace them with the values we send you.

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:

  1. Get your operator id, public key, widget origin and the wrapper file from your SensibleStats contact.
  2. Ask your contact to switch mobile on for your account.
  3. Add the file, create one SensibleStatsChat with the signed-in visitor's id, and show the sheet.
  4. Set onAddToSlip, then test an add, a duplicate and a reject.
  5. 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 page https://your-widget-host/m in a WKWebView and 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.
  • matchOddsId is your sportsbook's own id for one selection: one outcome of one market.
  • operatorUserId is 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 usExampleWhat it is
Operator idYOUR_OPERATOR_IDYour account in our system. Part of every request.
Public keyYOUR_PUBLIC_KEYIdentifies your widget.
Widget originhttps://your-widget-hostThe address the chat page is served from. Must be https.
WrapperSensibleStatsChat.swiftThe file you add to your app.
To usWhy
Ask your contact to switch mobile on for your accountUntil 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:

RequirementValue
iOS16.4 or later
SwiftSwift 5.7 or later compiler (the file is written in Swift 5 language mode)
FrameworksSwiftUI, UIKit, WebKit (all part of iOS)
A signed-in visitorRequired. 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:

Swift
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:

Swift
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#

FieldTypeWhat it does
baseUrlURLThe 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.
operatorIdStringYour operator id.
publicKeyStringYour public key. Empty operatorId or publicKey gives auth_failed.
userContextSensibleStatsConfig.UserContext.init(operatorUserId: String), the signed-in visitor. See section 5.

Visitor, language and time#

FieldTypeDefaultWhat it does
localeString?your account's default language (English unless you asked for another)The language of the chat and its answers, e.g. en-GB, tr.
timeZoneString?the device's zoneIANA zone, e.g. Europe/Istanbul. Kick-off times and day names follow it.
oddsFormatSensibleStatsChat.OddsFormat?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#

FieldTypeDefaultWhat it does
greetingMessageString?nilSent once when the page loads; the answer becomes the teaser. Use "hello". Without it there is no greeting and no teaser.
pageSensibleStatsChat.PageContext?nilThe screen the visitor is on, so the greeting can lead with it. Section 6.
placeholderString?localizedText in the empty question box.
starters[String]?nilSuggested questions shown in an empty chat.

Look#

FieldTypeDefaultWhat it does
themeSensibleStatsConfig.Theme.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.
colorsSensibleStatsConfig.Colors?nil.init(light:dark:), each a ThemeColors?. Section 10.
logoUrlString?our markYour square logo, shown on the icon and in the chat header. The icon loads only https: and data: URLs.
headerTitleString?SensibleStatsThe chat's title.
positionSensibleStatsConfig.Position.right.left or .right: which bottom corner the icon sits in.
offsetSensibleStatsConfig.Offset.init(x: 20, y: 20)Distance in points from the side and from the bottom of the view the icon overlays.
radiusDouble?16Corner radius of the chat panel, in points. Negative or non-finite values are dropped.
launcherBooltruefalse hides our icon and teaser so you draw your own (section 8).
launcherLabelString?"Chat with SensibleStats", localizedThe icon's label for VoiceOver. Until the page answers, the icon's label is English "Open chat"; to change that, set the sensiblestats.launcher.label string in your Localizable.strings.
pinIconSensibleStatsConfig.PinIcon?.pin.pin, .star or .bookmark: the icon visitors tap to follow a match or price.

Slip, callbacks and events#

FieldTypeDefaultWhat it does
slipSports[SensibleStatsChat.SlipSport]?nil.basketball, .americanfootball, .tennis: the sports your onAddToSlip accepts besides football. Section 7.
eventTextBoolfalseAdds 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:

PropertySwift typeWhat it does
onAddToSlip(Selection) async -> SlipResult?Adds a price to your bet slip. Section 7.
onTeaser(Teaser?) -> VoidGives you the teaser to draw yourself. Section 8.
onUnavailable(UnavailableReason) -> VoidTells you the chat cannot start. Section 11.
onEvent([String: Any]) -> VoidEvery 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:

Swift
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:

Swift
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.

Swift
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:

FieldTypeDefaultMeaning
sportSensibleStatsChat.Sportrequired.football, .basketball, .americanfootball, .tennis.
kindSensibleStatsChat.PageKind?nil.section, .competition or .match: a sport's front page, a competition page, or a match page.
matchIdSensibleStatsChat.PageId?nilYour sportsbook's id for the match on a match page.
competitionIdSensibleStatsChat.PageId?nilYour 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:

  1. The visitor taps "Add to slip" under a price.
  2. The wrapper calls onAddToSlip(selection). selection.matchOddsId is your sportsbook's own id for that selection, so you can look it up directly.
  3. Your code adds that selection to your slip and returns a SlipResult.
  4. The chat shows the visitor a short note in their language, such as "Added to slip".
Swift
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

FieldTypeMeaning
matchOddsIdIntYour sportsbook's id for the selection. Look it up in your slip.
matchIdIntYour sportsbook's id for the match.
oddsDecimalDoubleThe price the visitor saw, as a decimal.
sportSensibleStatsChat.Sport?nil (or .football) means football. .basketball, .americanfootball or .tennis otherwise.
tourString?Tennis only: the tour the match id belongs to.
oddsSlipOdds?The same price in your account's odds format (not the visitor's own choice): format (e.g. "american") and text (e.g. "+150").
quotedAtUtcString?ISO time when that price was last confirmed.
conversationId, insightIdString?Which chat and which card the tap came from.
displaySlipDisplay?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

ReturnWhenThe visitor sees (English)
.added() or nilThe selection is in the slip. .added(slip:) also takes a SlipSummary(selectionCount:totalOddsDecimal:); it is accepted but not shown today.Added to slip
.duplicateIt was already in the slip.Already in your slip
.priceChanged(newOdds: "2.10", accepted: true)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(newOdds: "2.10", accepted: false)The price moved and you did not add it.Price moved to 2.10 (was 1.95). Tap to add.
.rejected(reason:message:)You did not add it. reason is a RejectReason; message is optional.See below
RejectReasonMeaningThe visitor sees (English)
.loginRequiredThe visitor must sign in first.Sign in to add to your slip
.suspendedThe market is suspended.Market suspended
.closedThe market or match is closed, e.g. it has started.Your message, else "This selection can't be added."
.notFound, .limit, .unsupportedYou 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:

Swift
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.

CallWhen
chat.slipRemoved(.init(matchOddsId: id))The visitor removed a selection from your slip.
chat.betPlaced([.init(matchOddsId: id)], stake: 10, currency: "EUR", betId: "B123", betType: "single", totalOdds: 2.5)The visitor placed a bet. Only the selections are required; a non-finite stake or totalOdds is left out.
chat.matchOpened(matchId: id)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:

Swift
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:

FieldTypeMeaning
textString?The greeting line.
asks[Teaser.Ask]Suggested questions, each index: Int and label: String. Show label; pass index to tapAsk(index:).
ctaString?A button label, e.g. "Build a bet".
priceTeaserPrice?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:

CallWhenWhat the chat does
chat.teaserShown()You showed the teaser.Counts it as seen (once per teaser).
chat.tapTeaser()The visitor tapped the teaser text.Opens the chat.
chat.tapAsk(index:)The visitor tapped a suggested question.Opens the chat and asks it.
chat.tapCta()The visitor tapped the button.Opens the chat on it.
await chat.tapPrice()The visitor tapped the price.Checks the price again, then calls your onAddToSlip. Returns PriceResult?.
chat.dismissTeaser()The visitor closed the teaser.Clears it; onTeaser(nil) follows.
chat.open(), chat.close()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.

Swift
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.

EventFields
widget_opensource? (launcher, bubble, teaser, host, popup), first?
widget_closemethod (button, escape, host for your close(), native, back), tab, answering, openMs?
bubble_shown, bubble_click, bubble_dismissnone
bubble_ask_clickposition
tab_changefrom, to, source? (bar, link, auto)
question_askedturnId, source, length, text? (only with eventText), method?, chipId?, position?, actionRef?, retryOf?, matchId?
answer_receivedturnId, conversationId, latencyMs, cardTypes, firstByteMs?
answer_failedturnId, code
answer_stoppedturnId
add_to_slip_clickmatchOddsId, matchId, odds, market?, sport?, factKey?, surface?, turnId?
add_to_slip_resultthe same fields, plus outcome
pin_clickaction (add, remove), target (match, market), matchId?, market?, sport?, surface?, turnId?
combo_add_clicksurface (builder, chat), sport, legs, total, turnId?
combo_variant_clicksurface, sport, legs, total, variant
combo_swap_clicksurface, sport, legs, total
all_markets_clickmatchId, market?, surface
dashboard_tile_clickentityType, entityId
sport_switchsport
new_conversationnone
favourite_changekind, 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.

ColourUsed forLight defaultDark default
accentYour brand colour: links, highlights and the teaser's suggested questions.#17936a#37c891
ctaPrice and "Add to slip" buttons.#f5a623#ffb638
surfaceBackgrounds: the chat, the icon and the teaser.#ffffff#141b24
inkText.#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.

Swift
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.

UnavailableReasonRaw valueCauseFix
.noUserno_useruserContext.operatorUserId is empty, for example after sign-out.Pass the signed-in visitor's id (section 5).
.mobileDisabledmobile_disabledMobile is not switched on for your account.Ask your SensibleStats contact to switch mobile on for your account.
.widgetDisabledwidget_disabledThe 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.
.authFailedauth_failedThe 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:

MessageCause
baseUrl needs a hostbaseUrl has no host.
baseUrl cannot change on reload: create a new SensibleStatsChat for another originreload(config:) 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):

PropertyTypeMeaning
isOpenBool (read and write)Whether the chat is open. Bind your sheet to $chat.isOpen.
availableBoolThe chat is ready (section 11).
unavailableReasonUnavailableReason?Why it cannot start (section 11).
teaserTeaser?The current teaser (section 8).
pricePendingBoolA tapPrice() is running.
priceNoteString?The note from the last tapPrice().
configSensibleStatsConfigThe config in use.
labelsLauncherLabels?VoiceOver labels for the icon and teaser close button, in the visitor's language.
pageThemeSensibleStatsConfig.Theme?The theme the chat is showing, once it says.
webViewWKWebViewThe chat's web view, for ChatSheet.
wrapperVersionString, staticThe wrapper's version (section 3).

Methods:

MethodReturnsWhat it does
open(), close()nothingOpens or closes the chat.
reload(config:)nothingLoads the chat again with a new config (section 5).
setPage(_:)nothingSets the page (section 6); nil clears it.
slipRemoved(_:), betPlaced(_:stake:currency:betId:betType:totalOdds:), matchOpened(matchId:)nothingSection 7.
teaserShown(), tapTeaser(), tapAsk(index:), tapCta(), dismissTeaser()nothingSection 8.
tapPrice()async PriceResult?Section 8.

Callbacks: onAddToSlip, onTeaser, onUnavailable, onEvent (section 4). onBridgeMessage is for our own debugging; leave it unset.