Files
public-sdks-score/INTEGRATION.md
Blake ca717e4656 Publish Score iOS SDK 0.1.0 (SPM package + podspec + docs)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-06 01:27:14 -04:00

194 lines
7.3 KiB
Markdown

# Mobile SDK — Integration Guide (iOS + Android)
The Score mobile tracker is one Kotlin Multiplatform core shipped as a native
**iOS framework** (`ScoreTrackerKit`, fronted by the Swift `ScoreClient` facade)
and a native **Android AAR**. It emits the **same event envelope** as the web
tracker (`@3halves-labs/score-tracker`), so app events fire challenges/goals
identically — see [`conformance/CONTRACT.md`](conformance/CONTRACT.md).
---
## Install — 0.1.0 beta (hosted on Gitea)
Everything is hosted on the org's Gitea — no external registry. The Android
artifacts live in **Gitea's Maven package registry**; the iOS XCFramework is a
**Gitea release asset** (`mobile-v0.1.0`).
### Android — Gradle (Gitea Maven registry)
```kotlin
repositories {
maven {
url = uri("https://git.3halves-labs.com/api/packages/3HL-SCORE/maven")
// If the package registry isn't public, add a Gitea token:
// credentials(HttpHeaderCredentials::class) { name = "Authorization"; value = "token ${'$'}giteaToken" }
// authentication { create<HttpHeaderAuthentication>("header") }
}
}
dependencies {
implementation("com.threehalveslabs.scoretracker:shared-android:0.1.0")
}
```
### iOS — CocoaPods (release asset)
```ruby
pod 'ScoreTracker',
:podspec => 'https://git.3halves-labs.com/3HL-SCORE/score-anything-loyalty/raw/branch/main/mobile/ios/ScoreTracker/ScoreTracker.podspec'
```
### iOS — Swift Package Manager (Gitea Swift registry)
Published to Gitea's **Swift package registry** as `threehalveslabs.ScoreTracker`.
Configure the registry once (per machine / CI), then add it as a normal
dependency by **id** — no git URL needed:
```bash
swift package-registry set https://git.3halves-labs.com/api/packages/3HL-SCORE/swift
# private registry → log in with a Gitea token:
swift package-registry login https://git.3halves-labs.com/api/packages/3HL-SCORE/swift --token <gitea-token>
```
```swift
// your app's Package.swift
dependencies: [ .package(id: "threehalveslabs.ScoreTracker", from: "0.1.0") ]
// then: .product(name: "ScoreTracker", package: "ScoreTracker")
```
The package's binary `ScoreTrackerKit` target pulls the XCFramework from the
`mobile-v0.1.0` release asset (SPM verifies the checksum). For a private release
asset, SPM reads credentials from `~/.netrc`.
> Note: SPM-by-git-URL isn't available (the package lives in a monorepo subdir,
> which SPM can't resolve) — the Swift registry above is the supported path.
### iOS — direct XCFramework
Download `ScoreTrackerKit.xcframework.zip` from the **mobile-v0.1.0** release and
drag the `.xcframework` into your Xcode project; add `ScoreClient.swift`.
---
## iOS (Swift)
```swift
import ScoreTracker // the Swift facade (wraps the ScoreTrackerKit framework)
let score = ScoreClient(
publishableKey: "pk_live_…",
siteId: "urc-ios",
endpoint: "https://<middleware-host>",
sdkVersion: "0.1.0",
appVersion: Bundle.main.shortVersion,
os: "iOS \(UIDevice.current.systemVersion)",
device: UIDevice.current.model,
locale: Locale.current.identifier
)
// Nothing sends until consent is granted (see Consent below).
score.grantAllConsent()
// Track app earning events
score.track("poll_vote", props: ["pollId": "motm-r12", "choice": "player_7"])
score.screen("match_centre")
// Flush is async; the SDK also auto-flushes (see Offline & flushing)
Task { try? await score.flush() }
```
The durable offline queue and persistent `anonymousId` are handled natively
(NSUserDefaults) — events survive app cold starts and flush when back online.
## Android (Kotlin)
The shared core is already idiomatic Kotlin — no facade needed; construct via the
`newScoreTracker(context, …)` factory (uses SharedPreferences + OkHttp):
```kotlin
import com.threehalveslabs.scoretracker.*
val score = newScoreTracker(
context = applicationContext,
config = TrackerConfig(
publishableKey = "pk_live_…",
siteId = "urc-android",
endpoint = "https://<middleware-host>",
sdk = SdkInfo("@3halves-labs/score-tracker-android", "0.1.0"),
device = DeviceDescriptor(os = "Android ${Build.VERSION.RELEASE}", device = Build.MODEL,
appVersion = BuildConfig.VERSION_NAME, locale = Locale.getDefault().toLanguageTag()),
),
)
score.setConsent(ConsentState.ALL)
// Either a string name…
score.track("poll_vote", mapOf("pollId" to "motm-r12", "choice" to "player_7"))
// …or a typed definition from the generated `Events` taxonomy (preferred): the
// wire name + consent `requires` come from the shared schema, so app + web emit
// byte-identical events (#206). Same `Events` exist in the web tracker.
score.track(Events.PollVote, mapOf("pollId" to "motm-r12", "choice" to "player_7"))
// flush()/shutdown() are suspend — call from a coroutine
lifecycleScope.launch { score.flush() }
```
> `Events` (`Events.PollVote`, `Events.SportsPrediction`, `Events.SocialShare`,
> `Events.ArticleRead`, `Events.ProductView`, `Events.VideoWatch`,
> `Events.ProfileFavouriteTeam`, …) is generated from `sdk/schemas/events/*.schema.json`
> via `npm run gen:events`. **Don't edit `Events.kt` by hand** — edit the schema and
> regenerate; the web-side drift guard keeps it in lockstep.
---
## Consent (wire to your CMP / OneTrust)
Mirrors the web tracker (#108): the tracker is **idle until consent is granted**,
and pre-consent events are **dropped, not buffered**. Update consent whenever the
user's CMP choice changes.
```swift
// iOS in your CMP's "consent changed" callback:
score.setConsent(analytics: groups.analytics, personalization: groups.personalization, advertising: groups.advertising)
```
```kotlin
// Android:
score.setConsent(ConsentState(analytics = a, personalization = p, advertising = ad))
```
Events declaring a category (e.g. `trackAdvertising(...)` on iOS, or
`requires = listOf(ConsentCategory.ADVERTISING)` on Android) are dropped until
that category is granted.
## Auth0 (JWT)
Mirrors the web tracker (#109): supply a token provider — it's consulted before
each flush, so flushes carry a fresh access token. Failure → anonymous, never
halts.
```swift
score.setTokenProvider { Auth0Session.shared.accessToken } // called before each flush
score.identify(userId: "auth0|abc123") // optional: set userId now
```
```kotlin
score.setTokenProvider { auth0.credentials?.accessToken }
score.identify("auth0|abc123")
```
## Offline & flushing
- **Durable queue:** events persist (NSUserDefaults / SharedPreferences), survive
cold start, are FIFO-capped (oldest dropped), and clear only on a successful
POST (a failed flush retains them for retry).
- **Auto-flush:** `score.startAutoFlush(everySeconds: 30)` (iOS) /
`score.startAutoFlush(scope, intervalMs)` (Android).
- **Lifecycle hooks:** call `onForeground()` / `onNetworkAvailable()` to flush
promptly — wire them to `UIApplication`/`NWPathMonitor` (iOS) or
`ProcessLifecycleOwner`/connectivity callbacks (Android).
## Canonical app earning events
`type: "track"` with these names (props open; matched by the Odoo rules engine):
| `name` | example props |
| --- | --- |
| `poll_vote` | `{ pollId, choice }` |
| `motm_submit` | `{ matchId, playerId }` |
| `player_rating` | `{ matchId, playerId, rating }` |
| `minigame_play` | `{ game, result, score }` |
| `streak_tick` | `{ streakType, currentDays }` |
See [`conformance/fixtures/`](conformance/fixtures/) for full golden envelopes.