The SDK automatically flushes on UIApplication.didEnterBackgroundNotification (iOS). For SwiftUI apps, you can also flush when the scene becomes inactive:
swift
import SwiftUI
import SegOps
@main
struct MyApp: App {
let segops = SegOpsClient(options: .init(
apiURL: URL(string: "https://api.segops.ai")!,
apiKey: "sk_..."
))
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
ContentView()
}
.onChange(of: scenePhase) { phase in
if phase == .background || phase == .inactive {
segops.flush()
}
}
}
}
A secret key (sk_…) must never ship inside an app binary — anyone can extract it. Instead, create a public key (pk_…), which is safe to embed. When the apiKey starts with pk_, the SDK runs the session handshake: it exchanges the key for a short-lived JWT via POST /api/auth/session/, caches it, and re-mints on expiry/401 — all transparently.
To bind events to a logged-in user, sign the user_id on your backend (HMAC-SHA256 over "\(userId)|\(unixSeconds)" with the key's HMAC secret) and return it from userProvider:
swift
let segops = SegOpsClient(options: .init(
apiURL: URL(string: "https://api.segops.ai")!,
apiKey: "pk_...",
userProvider: {
SegOpsUserContext(
userId: currentUser.id,
userIdSig: signed.sig, // from your backend
userIdTs: signed.ts
)
}
))
For anonymous visitors, omit userProvider (or return SegOpsUserContext(anonymousId:)).
✦ Tip
Enable "require signed user_id" on the public key so the server rejects unsigned or forged identities. Keys used by mobile apps should have an empty origin allowlist (mobile clients send no Origin header).
Flush all buffered events immediately (fire-and-forget, runs on a background URLSession task).
swift
segops.flush()
✦ Tip
On iOS the SDK flushes automatically on background. For macOS / pure-SwiftUI apps that don't use UIKit, call flush() manually when appropriate (e.g. in a .onChange(of: scenePhase) handler).
public struct SegOpsEvent: Sendable {
public let userId: String
public let eventType: String
public let occurredAt: Date? // defaults to now
public let payload: [String: any Sendable]
}
public struct SegOpsContext: Sendable {
public let userId: String
public let traits: [String: any Sendable]
}
// Supplied to userProvider when authenticating with a pk_ key.
public struct SegOpsUserContext: Sendable {
public let userId: String? // omit for anonymous visitors
public let anonymousId: String?
public let userIdSig: String? // hex HMAC signature from your backend
public let userIdTs: Int? // unix-seconds paired with userIdSig
}