iOS (Swift)
Swift package for iOS, iPadOS, macOS, tvOS, watchOS and visionOS, in SwiftUI or UIKit.
Screen views, custom events, users, revenue and feature flags, with an offline queue. No third-party dependencies, no IDFA, and a privacy manifest included. Swift 5.9 (Xcode 15) or later; iOS 13, macOS 10.15, tvOS 13, watchOS 7, visionOS 1. Read Mobile apps for how sessions, screens and offline delivery work.
Install from source
The package lives in packages/swift of the Stancelens repository and isn't published at a SwiftPM URL yet, so add it as a local package from a checkout:
- Xcode: File → Add Package Dependencies → Add Local, choose the
packages/swiftfolder, and add theStancelenslibrary to your app target. - Or in
Package.swift:
dependencies: [
.package(path: "../stancelens/packages/swift"),
],
targets: [
.target(name: "MyApp", dependencies: [.product(name: "Stancelens", package: "Stancelens")]),
]Quick start (SwiftUI)
import SwiftUI
import Stancelens
@main
struct MyApp: App {
init() {
Stancelens.configure(site: "SITE_ID", host: "https://stancelens.com")
}
var body: some Scene {
WindowGroup { ContentView() }
}
}
struct ContentView: View {
var body: some View {
NavigationStack {
List {
NavigationLink("Settings") {
SettingsView().trackScreen("Settings")
}
}
.trackScreen("Home")
}
}
}
struct SettingsView: View {
var body: some View {
Button("Upgrade") {
Stancelens.track("Upgrade tapped", properties: ["plan": "pro"])
}
}
}host is the base URL of your Stancelens server: events go to <host>/api/event and flags come from <host>/api/flags.
UIKit
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Stancelens.screen("Checkout")
}Or turn on automatic screen tracking. It swaps UIViewController.viewDidAppear(_:) once at startup (method swizzling), which is why it's off by default:
Stancelens.configure(
site: "SITE_ID",
host: "https://stancelens.com",
configuration: Configuration(automaticScreenTracking: true)
)
// Choose the name, or return nil to skip a controller
extension ProductViewController: StancelensScreenNameProviding {
var stancelensScreenName: String? { "Product" }
}Each view controller is recorded under its class name without the ViewController or Controller suffix (CheckoutViewController becomes Checkout). Navigation, tab, split and page controllers and Apple's own controllers are skipped.
API
// Setup (once, at launch)
Stancelens.configure(site: String, host: String, configuration: Configuration = Configuration())
// Tracking
Stancelens.screen(_ name: String, properties: StancelensProperties = [:])
Stancelens.track(_ name: String, properties: StancelensProperties = [:])
Stancelens.identify(_ userId: String, traits: StancelensProperties = [:])
Stancelens.revenue(_ amount: Double, currency: String, properties: StancelensProperties = [:], event: String = "purchase")
Stancelens.reset()
// Feature flags
await Stancelens.flag(_ key: String) -> FlagValue? // .on, .off or .variant("test")
Stancelens.cachedFlag(_ key: String) -> FlagValue? // no request, no exposure
await Stancelens.reloadFlags()
// Delivery and consent
await Stancelens.flush()
Stancelens.optOut()
Stancelens.optIn()
Stancelens.isOptedOut: Bool
// IDs
Stancelens.visitorId: String?
Stancelens.sessionId: String?
// Only where the SDK can't see the app lifecycle (app extensions, command-line tools)
Stancelens.didEnterBackground()
Stancelens.willEnterForeground()
// SwiftUI
View.trackScreen(_ name: String, properties: StancelensProperties = [:])- Calls are safe from any thread or task and are recorded in order, with the time they were made. Calls before
configureare ignored. - Properties and traits take literals: strings, integers, doubles, booleans and
nil. identifyattaches the user ID to every later event, across launches.reset()on sign-out clears it and starts a new anonymous ID and session.revenue(29.99, currency: "USD")records apurchaseevent; passevent:for another name. A currency that isn't three letters falls back to the site currency.
Feature flags
if await Stancelens.flag("new-checkout")?.isEnabled == true { ... }
switch await Stancelens.flag("pricing-test") {
case .variant("test"): showNewPricing()
default: showCurrentPricing()
}The first flag(_:) call fetches every flag for the visitor (or user) in one request. Values are cached on disk and fetched again after flagCacheTTL (5 minutes) or when the user changes; offline, the last known value is returned. nil means the flag doesn't exist or flags have never loaded. An $exposure is recorded once per flag value per session.
Delivery
- Events are written to a queue file in Application Support (at most once a second, and immediately when the app goes to the background). Up to
maxQueueSize(1,000) are kept; beyond that the oldest are dropped. - Batches of up to
maxBatchSize(50) go out whenflushAt(20) are waiting, everyflushInterval(30 s) in the foreground, onflush(), and when the app goes to the background (with a background task on iOS, tvOS and visionOS). - Network errors, timeouts, 408, 429 and 5xx keep the batch and retry after 2 s, 4 s, 8 s… up to 5 minutes, with jitter. Other 4xx responses drop it.
- Requests use an ephemeral
URLSession: no cookies, no cache. - Each event carries the time it happened (
ts), an event ID and, per request,sent_at, so the server drops a repeat and corrects a wrong device clock. The server accepts events up to 72 hours old; older ones are dropped (offline delivery). - Sessions end after 30 minutes without events, background time included (
sessionTimeout), and continue across a relaunch within that time.
What is sent
| Field | Example | Notes |
|---|---|---|
vid | 9a9dac11da08… | Random ID created on first launch, kept in UserDefaults. Not derived from any device identifier. New after reset(). |
uid | user_42 | Only after identify. |
session_id | 8e0489d980c1… | SDK-owned session. |
path, title | /Settings, Settings | From screen(_:). |
platform | ios | On every Apple platform. |
os, os_version | iPadOS, 17.4 | iOS, iPadOS, macOS, tvOS, watchOS or visionOS. |
device_model | iPhone16,2 | Hardware identifier. |
device_type | mobile | mobile (iPhone, Apple Watch), tablet (iPad), desktop (Mac, Vision Pro), tv. |
app_version | 2.4.1 (318) | CFBundleShortVersionString (CFBundleVersion). |
language, timezone | en-US, Europe/Berlin | |
screen | 393x852 | Screen size in points (not on visionOS). |
sdk | stancelens-swift/1.0.0 |
Privacy
PrivacyInfo.xcprivacyships with the package: no tracking, no tracking domains, and the collected types product interaction, device ID (the randomvid), user ID (only afteridentify), purchase history (only withrevenue) and coarse location. Only the user ID is linked to identity. The one required-reason API it uses is UserDefaults (CA92.1, and1C8F.1for App Groups). Xcode merges it into your app's privacy report.- No IDFA, no IDFV, no fingerprinting, so the SDK doesn't need the App Tracking Transparency prompt on its own account.
optOut()stops collection, deletes queued events and is remembered across launches. While opted out,flag(_:)makes no requests and returns only cached values.
App extensions
Set Configuration(appGroup: "group.com.example.app") in the app and its extensions to share the anonymous ID, user ID and opt-out choice. Each process keeps its own queue file in the group container. Extensions can't be observed going to the background, so call await Stancelens.flush() when an extension finishes its work.
Configuration
| Option | Default | |
|---|---|---|
flushAt | 20 | Send when this many events are queued. |
flushInterval | 30 s | Periodic send in the foreground; 0 turns it off. |
maxBatchSize | 50 | Events per request (1 to 100). |
maxQueueSize | 1000 | Events kept offline. |
sessionTimeout | 30 min | Inactivity that ends a session. |
flagCacheTTL | 5 min | Age at which flags are fetched again. |
appGroup | nil | Share IDs and opt-out with extensions. |
automaticScreenTracking | false | UIKit screen views via swizzling. |
debug | false | Log to the console. |