Publish Score iOS SDK 0.3.0
This commit is contained in:
104
Sources/ScoreTracker/AppLifecycle.swift
Normal file
104
Sources/ScoreTracker/AppLifecycle.swift
Normal file
@@ -0,0 +1,104 @@
|
||||
import Foundation
|
||||
import Network
|
||||
import ScoreTrackerKit
|
||||
import UIKit
|
||||
|
||||
/// Everything `bindToAppLifecycle()` installed, so `unbindAppLifecycle()` can
|
||||
/// remove exactly that (#484).
|
||||
final class AppBindings {
|
||||
let controller: AppLifecycleController
|
||||
var observers: [NSObjectProtocol] = []
|
||||
var pathMonitor: NWPathMonitor?
|
||||
var networkWasSatisfied = true
|
||||
|
||||
init(controller: AppLifecycleController) { self.controller = controller }
|
||||
}
|
||||
|
||||
extension ScoreClient {
|
||||
|
||||
/// Flush on the app's lifecycle and connectivity, so you don't wire them by
|
||||
/// hand (#484). One call, opt-in — typically in
|
||||
/// `application(_:didFinishLaunchingWithOptions:)`:
|
||||
///
|
||||
/// score.bindToAppLifecycle()
|
||||
///
|
||||
/// - Foreground (`willEnterForeground`, or already active when you bind):
|
||||
/// flush, and flush every `autoFlushEverySeconds` (nil: leave auto-flush
|
||||
/// to you).
|
||||
/// - Background (`didEnterBackground`): stop the periodic flush, then a
|
||||
/// best-effort flush bounded by `backgroundBudgetSeconds`, inside a
|
||||
/// background task that ends as soon as the flush does.
|
||||
/// - Network back (`NWPathMonitor` turns satisfied): flush.
|
||||
///
|
||||
/// The behaviour is the shared `AppLifecycleController`, the same one the
|
||||
/// Android binding drives. Call on the main thread. If you use
|
||||
/// `startAutoFlush(everySeconds:)` yourself, binding with an interval
|
||||
/// replaces it; pass `autoFlushEverySeconds: nil` to keep yours.
|
||||
@available(iOSApplicationExtension, unavailable, message: "App lifecycle notifications aren't delivered to extensions; flush manually.")
|
||||
public func bindToAppLifecycle(autoFlushEverySeconds: Double? = 30, backgroundBudgetSeconds: Double = 5) {
|
||||
dispatchPrecondition(condition: .onQueue(.main))
|
||||
unbindAppLifecycle()
|
||||
if autoFlushEverySeconds != nil { stopAutoFlush() } // one periodic flush, not two
|
||||
|
||||
let controller = IosPlatformKt.doNewAppLifecycleController(
|
||||
tracker: tracker,
|
||||
autoFlushIntervalMs: Int64((autoFlushEverySeconds ?? 0) * 1000), // 0 → none
|
||||
backgroundBudgetMs: Int64(backgroundBudgetSeconds * 1000)
|
||||
)
|
||||
let bindings = AppBindings(controller: controller)
|
||||
let center = NotificationCenter.default
|
||||
|
||||
bindings.observers.append(center.addObserver(
|
||||
forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main
|
||||
) { _ in controller.appDidEnterForeground() })
|
||||
|
||||
bindings.observers.append(center.addObserver(
|
||||
forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main
|
||||
) { _ in
|
||||
// Ask iOS for time to finish the flush; hand it back the moment the
|
||||
// bounded flush is done (or, if iOS's own deadline comes first, then).
|
||||
var task = UIBackgroundTaskIdentifier.invalid
|
||||
let end = {
|
||||
guard task != .invalid else { return }
|
||||
UIApplication.shared.endBackgroundTask(task)
|
||||
task = .invalid
|
||||
}
|
||||
task = UIApplication.shared.beginBackgroundTask(withName: "ScoreTracker.flush", expirationHandler: end)
|
||||
controller.appDidEnterBackground(onDone: end)
|
||||
})
|
||||
|
||||
// Android parity: binding while already in the foreground counts as one.
|
||||
if UIApplication.shared.applicationState == .active {
|
||||
controller.appDidEnterForeground()
|
||||
}
|
||||
|
||||
// Flush on the transition to "satisfied", not on every path update.
|
||||
let monitor = NWPathMonitor()
|
||||
monitor.pathUpdateHandler = { [weak bindings] path in
|
||||
DispatchQueue.main.async {
|
||||
guard let bindings else { return }
|
||||
let satisfied = path.status == .satisfied
|
||||
if satisfied && !bindings.networkWasSatisfied { bindings.controller.networkDidBecomeAvailable() }
|
||||
bindings.networkWasSatisfied = satisfied
|
||||
}
|
||||
}
|
||||
monitor.start(queue: DispatchQueue(label: "com.threehalveslabs.scoretracker.network"))
|
||||
bindings.pathMonitor = monitor
|
||||
|
||||
appBindings = bindings
|
||||
}
|
||||
|
||||
/// Remove everything `bindToAppLifecycle()` installed. Safe to call when not bound.
|
||||
public func unbindAppLifecycle() {
|
||||
dispatchPrecondition(condition: .onQueue(.main))
|
||||
unbindAppLifecycleFromAnyContext()
|
||||
}
|
||||
|
||||
func unbindAppLifecycleFromAnyContext() {
|
||||
guard let bindings = appBindings else { return }
|
||||
bindings.observers.forEach { NotificationCenter.default.removeObserver($0) }
|
||||
bindings.pathMonitor?.cancel()
|
||||
bindings.controller.close()
|
||||
appBindings = nil
|
||||
}
|
||||
}
|
||||
19
Sources/ScoreTracker/Exports.swift
Normal file
19
Sources/ScoreTracker/Exports.swift
Normal file
@@ -0,0 +1,19 @@
|
||||
import ScoreTrackerKit
|
||||
|
||||
// The types in ScoreClient's public API live in the ScoreTrackerKit framework.
|
||||
// The integration guide has apps `import ScoreTracker` only, which left them
|
||||
// unable to name any of these, so `Events.shared.PollVote` and
|
||||
// `requires: [ConsentCategory.advertising]` didn't compile in an app (#485).
|
||||
// Re-exported by name; an app that also imports ScoreTrackerKit sees the same
|
||||
// types, because a module's declarations shadow those of the modules it imports.
|
||||
|
||||
/// Generated loyalty event definitions (`Events.shared.PollVote`, …), shared
|
||||
/// with the web and Android trackers.
|
||||
public typealias Events = ScoreTrackerKit.Events
|
||||
public typealias EventDefinition = ScoreTrackerKit.EventDefinition
|
||||
public typealias ConsentCategory = ScoreTrackerKit.ConsentCategory
|
||||
public typealias ConsentState = ScoreTrackerKit.ConsentState
|
||||
public typealias DeliveryMode = ScoreTrackerKit.DeliveryMode
|
||||
public typealias PiiOptions = ScoreTrackerKit.PiiOptions
|
||||
public typealias PiiRule = ScoreTrackerKit.PiiRule
|
||||
public typealias PiiAction = ScoreTrackerKit.PiiAction
|
||||
@@ -7,14 +7,49 @@ import ScoreTrackerKit
|
||||
/// and persistent `anonymousId` are handled natively (NSUserDefaults) — see #176.
|
||||
public final class ScoreClient {
|
||||
|
||||
private let tracker: ScoreTracker
|
||||
let tracker: ScoreTracker
|
||||
private var autoFlushTask: Task<Void, Never>?
|
||||
/// Set while `bindToAppLifecycle()` is in effect (AppLifecycle.swift, #484).
|
||||
var appBindings: AppBindings?
|
||||
|
||||
/// - Parameters:
|
||||
/// - endpoint: middleware base URL; events POST to `<endpoint>/api/tracking/website`.
|
||||
/// - initialConsent: defaults to "none" — nothing fires until `setConsent(...)`.
|
||||
/// - pii: field-level PII handling (#482), scrubbed before events are queued on the device.
|
||||
/// - tokenRefreshTimeoutSeconds: how long a flush waits for the token provider (#483).
|
||||
///
|
||||
/// The envelope's `sdk.name` / `sdk.version` are baked into the framework
|
||||
/// (#486); there is nothing to pass.
|
||||
public init(
|
||||
publishableKey: String,
|
||||
siteId: String,
|
||||
endpoint: String,
|
||||
appVersion: String? = nil,
|
||||
os: String? = nil,
|
||||
device: String? = nil,
|
||||
locale: String? = nil,
|
||||
initialConsent: ConsentState = ConsentState.companion.NONE,
|
||||
pii: PiiOptions? = nil,
|
||||
tokenRefreshTimeoutSeconds: Double = 5
|
||||
) {
|
||||
let config = TrackerConfig(
|
||||
publishableKey: publishableKey,
|
||||
siteId: siteId,
|
||||
endpoint: endpoint,
|
||||
device: DeviceDescriptor(os: os, device: device, appVersion: appVersion, locale: locale)
|
||||
)
|
||||
tracker = IosPlatformKt.doNewScoreTracker(
|
||||
config: config,
|
||||
initialConsent: initialConsent,
|
||||
pii: pii,
|
||||
tokenRefreshTimeoutMs: Int64(tokenRefreshTimeoutSeconds * 1000)
|
||||
)
|
||||
}
|
||||
|
||||
/// The pre-#486 signature. `sdkVersion` is ignored: the SDK reports the
|
||||
/// version it was built as.
|
||||
@available(*, deprecated, message: "The SDK reports its own version now (#486); sdkVersion is ignored. Drop the argument.")
|
||||
public convenience init(
|
||||
publishableKey: String,
|
||||
siteId: String,
|
||||
endpoint: String,
|
||||
@@ -26,16 +61,17 @@ public final class ScoreClient {
|
||||
initialConsent: ConsentState = ConsentState.companion.NONE,
|
||||
pii: PiiOptions? = nil
|
||||
) {
|
||||
let config = TrackerConfig(
|
||||
publishableKey: publishableKey,
|
||||
siteId: siteId,
|
||||
endpoint: endpoint,
|
||||
sdk: SdkInfo(name: "@3halves-labs/score-tracker-ios", version: sdkVersion),
|
||||
device: DeviceDescriptor(os: os, device: device, appVersion: appVersion, locale: locale)
|
||||
self.init(
|
||||
publishableKey: publishableKey, siteId: siteId, endpoint: endpoint,
|
||||
appVersion: appVersion, os: os, device: device, locale: locale,
|
||||
initialConsent: initialConsent, pii: pii
|
||||
)
|
||||
tracker = IosPlatformKt.doNewScoreTracker(config: config, initialConsent: initialConsent, pii: pii)
|
||||
}
|
||||
|
||||
/// What this build reports as `sdk.name` / `sdk.version` — for support and logs.
|
||||
public static var sdkName: String { SdkInfo.companion.CURRENT.name }
|
||||
public static var sdkVersion: String { SdkInfo.companion.CURRENT.version }
|
||||
|
||||
// MARK: - Consent (wire to your CMP / OneTrust)
|
||||
|
||||
public func setConsent(analytics: Bool, personalization: Bool, advertising: Bool) {
|
||||
@@ -51,9 +87,21 @@ public final class ScoreClient {
|
||||
}
|
||||
public func setToken(_ token: String?) { tracker.setToken(token: token) }
|
||||
|
||||
/// Provider is consulted before each flush — wire to your Auth0 access token.
|
||||
public func setTokenProvider(_ provider: @escaping () -> String?) {
|
||||
tracker.setTokenProvider(provider: provider)
|
||||
/// Supply the fan's access token on demand — wire to Auth0's
|
||||
/// `credentialsManager.credentials()` (#483). `async`, so a silent refresh
|
||||
/// needs no blocking; a plain synchronous closure works too. Consulted
|
||||
/// before each flush, single-flight. If it throws, returns nil or takes
|
||||
/// longer than the tracker's timeout (5 s), the flush goes ahead with the
|
||||
/// last known token — anonymous if there is none.
|
||||
public func setTokenProvider(_ provider: @escaping () async throws -> String?) {
|
||||
tracker.setCallbackTokenProvider { complete in
|
||||
Task { complete(try? await provider()) } // a throw counts as "no token"
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop consulting a provider; the last token set stays until replaced.
|
||||
public func clearTokenProvider() {
|
||||
tracker.setCallbackTokenProvider(provider: nil)
|
||||
}
|
||||
|
||||
public var anonymousId: String { tracker.anonymousId }
|
||||
@@ -61,16 +109,35 @@ public final class ScoreClient {
|
||||
|
||||
// MARK: - Tracking
|
||||
|
||||
/// Track an app event. Returns false if dropped by the consent gate.
|
||||
/// Track a typed loyalty event — the preferred form (#485). `Events` is
|
||||
/// generated from the same schemas as the web and Android trackers, so the
|
||||
/// name and its consent contract (`requires`) are identical on every
|
||||
/// platform. Returns false if dropped by the consent gate.
|
||||
///
|
||||
/// score.track(Events.shared.PollVote, props: ["pollId": "motm-r12", "choice": "player_7"])
|
||||
@discardableResult
|
||||
public func track(_ name: String, props: [String: Any] = [:]) -> Bool {
|
||||
tracker.track(name: name, props: props, type: .track, requires: [], delivery: .bestEffort)
|
||||
public func track(_ event: EventDefinition, props: [String: Any] = [:], delivery: DeliveryMode = .bestEffort) -> Bool {
|
||||
tracker.track(event: event, props: props, delivery: delivery)
|
||||
}
|
||||
|
||||
/// Track an app event by name, for events not in `Events`. `requires` gates
|
||||
/// it on consent categories — it is dropped unless every one is granted.
|
||||
/// Returns false if dropped by the consent gate.
|
||||
@discardableResult
|
||||
public func track(
|
||||
_ name: String,
|
||||
props: [String: Any] = [:],
|
||||
requires: [ConsentCategory] = [],
|
||||
delivery: DeliveryMode = .bestEffort
|
||||
) -> Bool {
|
||||
tracker.track(name: name, props: props, type: .track, requires: requires, delivery: delivery)
|
||||
}
|
||||
|
||||
/// Track an event gated on advertising consent (dropped until granted).
|
||||
/// Shorthand for `track(name, props:, requires: [.advertising])`.
|
||||
@discardableResult
|
||||
public func trackAdvertising(_ name: String, props: [String: Any] = [:]) -> Bool {
|
||||
tracker.track(name: name, props: props, type: .track, requires: [ConsentCategory.advertising], delivery: .bestEffort)
|
||||
track(name, props: props, requires: [ConsentCategory.advertising])
|
||||
}
|
||||
|
||||
/// Record an app-screen view.
|
||||
@@ -91,9 +158,18 @@ public final class ScoreClient {
|
||||
public func onForeground() async throws { _ = try await tracker.onForeground() }
|
||||
/// Call when network connectivity is regained.
|
||||
public func onNetworkAvailable() async throws { _ = try await tracker.onNetworkAvailable() }
|
||||
/// Best-effort flush as the app goes to the background (#484), bounded by
|
||||
/// `budgetSeconds` so it cannot hold up suspension. Returns false if it ran
|
||||
/// out of time; unsent events stay queued. `bindToAppLifecycle()` calls this
|
||||
/// for you.
|
||||
@discardableResult
|
||||
public func onBackground(budgetSeconds: Double = 5) async throws -> Bool {
|
||||
try await tracker.onBackground(budgetMs: Int64(budgetSeconds * 1000)).boolValue
|
||||
}
|
||||
|
||||
public func shutdown() async throws {
|
||||
stopAutoFlush()
|
||||
await MainActor.run { unbindAppLifecycleFromAnyContext() }
|
||||
try await tracker.shutdown()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user