import Foundation #if canImport(UIKit) && !os(watchOS) import UIKit #endif /// Viewthrough SDK for Swift — installs, onboarding, paywall and checkout /// events from your app, batched and offline-safe. The same contract as /// `@viewthrough/sdk` (React Native), in one file. /// /// Identity is the heart of it, not the events. A `device_id` is made on the /// first start and kept in UserDefaults (survives logout, not reinstall) — /// that first start is the install. After login, `identify(_:)` adds the /// user id to everything from then on. Give RevenueCat the SAME id /// (`Purchases.shared.logIn(userId)`), or Viewthrough cannot tie purchases /// to installs. /// /// Only the money events exist (`Viewthrough.countEvents`). Anything else is /// rejected by the server on purpose: Viewthrough is not a product-analytics /// tool. Trials, purchases, cancellations and refunds come from the store via /// the RevenueCat webhook; `trial_started` and `purchase` here mean "what the /// app reported". /// /// Sending: events go to a queue on the device and leave in batches — after /// `flushAt` events (20) or every `flushInterval` (30 s), whichever comes /// first; `flush()` sends now, and the app going to the background sends /// too. Offline or server error: the queue stays, the SDK retries with /// backoff (1 s → 5 min). Nothing is dropped except when the queue exceeds /// `maxQueue` (then the oldest go) or when the server rejects a batch as /// malformed (HTTP 400). Every event has a UUID; a batch sent twice counts /// once. A wrong key (HTTP 401) stops sending until the next start. /// /// Consent: with `Options.requireConsent = true` nothing is written to /// UserDefaults and nothing is sent until `optIn()` — for apps whose consent /// dialog decides whether attribution may run (ePrivacy Art. 5(3), German /// TDDDG § 25). The choice is remembered; `optOut()` withdraws it. /// /// All work runs on one serial queue; no public method blocks the caller. public final class Viewthrough { public static let sdkName = "viewthrough-swift" public static let sdkVersion = "0.2.0" public static let defaultEndpoint = URL(string: "https://viewthrough.app/api/v1/events")! /// The events that count. `track(_:props:)` accepts nothing else. public static let countEvents: [String] = [ "install", "app_open", "onboarding_started", "onboarding_completed", "paywall_shown", "checkout_started", "trial_started", "purchase", ] static let controlEvents: [String] = ["identify", "set_attribution", "opt_out", "opt_in"] public static let platforms: [String] = ["ios", "android", "web", "unknown"] static let serverMaxBatch = 100 // MARK: - Options public struct Options { /// Defaults to https://viewthrough.app/api/v1/events. public var endpoint: URL = Viewthrough.defaultEndpoint /// Send after this many queued events (default 20, max 100). public var flushAt: Int = 20 /// Send at least this often while something is queued (default 30 s). public var flushInterval: TimeInterval = 30 /// Keep at most this many events offline (default 5000); the oldest go first. public var maxQueue: Int = 5000 /// Send `app_open` on every start (default true). public var trackAppOpen: Bool = true /// Wait for consent (default false): store nothing and send nothing /// until `optIn()`. The choice is remembered across starts. public var requireConsent: Bool = false /// Print what the SDK does. public var debug: Bool = false /// Defaults to CFBundleShortVersionString of the main bundle. public var appVersion: String? = Viewthrough.bundleVersion() /// Defaults to the running OS version, e.g. "18.1". public var osVersion: String? = Viewthrough.systemVersion() /// BCP-47, e.g. "de-DE". Defaults to the first preferred language. public var locale: String? = Viewthrough.preferredLocale() /// ios | android | web | unknown. Defaults to "ios" on iOS and Catalyst. public var platform: String = Viewthrough.defaultPlatform() /// Where device id and queue live. One suite per app is fine. public var userDefaults: UserDefaults = .standard /// The session used for sending (tests inject a stub). public var session: URLSession = .shared public init() {} } // MARK: - Shared instance /// Set by `configure(key:options:)`. Optional on purpose: an app that /// never configured the SDK should not crash on `Viewthrough.shared`. public private(set) static var shared: Viewthrough? /// Create the client once at app start and keep it as `shared`. @discardableResult public static func configure(key: String, options: Options = Options()) -> Viewthrough { let vt = Viewthrough(key: key, options: options) shared = vt return vt } /// Whether `key` looks like an SDK key from Sources → SDK (`vts_` + 43 chars). public static func isValidKey(_ key: String) -> Bool { guard key.hasPrefix("vts_"), key.count == 47 else { return false } let allowed = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") return key.dropFirst(4).allSatisfy { allowed.contains($0) } } // MARK: - State /// False when the key is not an SDK key: every call is then a no-op, so /// a misconfigured build never crashes in production. public let isEnabled: Bool private let key: String private let options: Options private let namespace: String private let work = DispatchQueue(label: "app.viewthrough.sdk", qos: .utility) private let workKey = DispatchSpecificKey() private var state: Persisted /// Whether `state` is in UserDefaults. False only while a fresh install waits for consent. private var onDisk: Bool private var events: [QueuedEvent] = [] private var attempt = 0 private var stopped = false private var closed = false private var flushing = false private var flushCompletions: [() -> Void] = [] private var timer: DispatchWorkItem? private var timerDueAt: Date? private var nextAllowedAt = Date.distantPast private var observers: [NSObjectProtocol] = [] public init(key: String, options: Options = Options()) { self.key = key var opts = options opts.flushAt = min(max(1, options.flushAt), Viewthrough.serverMaxBatch) if !Viewthrough.platforms.contains(opts.platform) { opts.platform = "unknown" } self.options = opts let valid = Viewthrough.isValidKey(key) self.isEnabled = valid let ns = valid ? "vt:" + String(key.dropFirst(4).prefix(8)) : "vt:invalid" self.namespace = ns let now = Date() var loaded = Persisted.load(from: opts.userDefaults, key: "\(ns):state") let firstStart = loaded == nil if loaded == nil { loaded = Persisted(deviceId: UUID().uuidString.lowercased(), installedAt: now) } self.state = loaded! self.onDisk = !firstStart work.setSpecific(key: workKey, value: 1) guard valid else { Viewthrough.warn("`key` must be the app's SDK key (vts_…) from Sources → SDK; the SDK is disabled") if NSClassFromString("XCTestCase") == nil { assertionFailure("[viewthrough] invalid SDK key") } return } work.async { self.events = QueuedEvent.loadQueue(from: opts.userDefaults, key: "\(ns):queue") if firstStart && self.pending { // Waiting for consent: the id lives in memory only, nothing is sent. self.debugLog("requireConsent: nothing is stored or sent until optIn()") return } if firstStart { // First start on this device: that is the install. self.persistState() self.enqueueNow("install", props: nil, userId: nil, at: now) } if self.pending { // Stored by an earlier version without consent, or consent // withdrawn: only a pending opt-out still leaves the device. let before = self.events.count self.events.removeAll { $0.event != "opt_out" && $0.event != "opt_in" } if self.events.count != before { self.persistQueue() } } else if opts.trackAppOpen && !self.state.optedOut { self.enqueueNow("app_open", props: nil, userId: nil, at: now) } self.schedule(0) } installLifecycleHooks() } deinit { for o in observers { NotificationCenter.default.removeObserver(o) } } // MARK: - Events /// Record one of the money events. Unknown names are logged and ignored. public func track(_ event: String, props: [String: Any] = [:]) { guard Viewthrough.countEvents.contains(event) else { Viewthrough.warn("track: \"\(event)\" is not a Viewthrough event; use one of \(Viewthrough.countEvents.joined(separator: ", "))") return } enqueue(event, props: props, userId: nil) } public func onboardingStarted(props: [String: Any] = [:]) { track("onboarding_started", props: props) } public func onboardingCompleted(props: [String: Any] = [:]) { track("onboarding_completed", props: props) } /// e.g. surface: "onboarding", "settings", "feature_gate" public func paywallShown(surface: String? = nil, props: [String: Any] = [:]) { track("paywall_shown", props: merge(props, ["surface": surface])) } public func checkoutStarted(productId: String? = nil, plan: String? = nil, props: [String: Any] = [:]) { track("checkout_started", props: merge(props, ["product_id": productId, "plan": plan])) } /// What the app saw. The store's view comes from RevenueCat. public func trialStarted(productId: String? = nil, props: [String: Any] = [:]) { track("trial_started", props: merge(props, ["product_id": productId])) } public func purchase(productId: String? = nil, plan: String? = nil, props: [String: Any] = [:]) { track("purchase", props: merge(props, ["product_id": productId, "plan": plan])) } /// Call on foreground if you want app opens beyond cold starts. public func appOpened() { track("app_open") } // MARK: - Identity /// After login. Use the same id for RevenueCat (`Purchases.shared.logIn`). public func identify(_ userId: String) { let id = userId.trimmingCharacters(in: .whitespacesAndNewlines) guard !id.isEmpty, id.count <= 128, id.rangeOfCharacter(from: .whitespacesAndNewlines) == nil else { Viewthrough.warn("identify: user id must be a non-empty string without whitespace (max 128)") return } guard isEnabled else { return } work.async { if self.pending || self.state.userId == id { return } self.state.userId = id self.persistState() self.enqueueNow("identify", props: nil, userId: id, at: Date()) } } /// On logout: forget the user id. The device id stays — it is still the same install. public func reset() { guard isEnabled else { return } work.async { self.state.userId = nil self.persistState() } } /// Where this install came from: the onboarding question /// (`acquisitionSource`) and/or the tracking-link campaign /// (`installUtmCampaign`). Stored on the device, not counted as an event. public func setAttribution(acquisitionSource: String? = nil, installUtmCampaign: String? = nil, extra: [String: Any] = [:]) { var raw = extra if let s = acquisitionSource { raw["acquisition_source"] = s } if let c = installUtmCampaign { raw["install_utm_campaign"] = c } let clean = Viewthrough.cleanProps(raw) guard !clean.isEmpty else { return } enqueue("set_attribution", props: clean, userId: nil) } /// Stop collecting and tell the server to drop this device from every /// count. Events still waiting on the device are discarded, not sent. /// Before any consent (`requireConsent`, nothing stored yet) there is /// nothing to undo. public func optOut() { guard isEnabled else { return } work.async { if self.state.optedOut || !self.onDisk { return } self.events = [] self.state.optedOut = true if self.options.requireConsent { self.state.consent = false } self.enqueueNow("opt_out", props: nil, userId: nil, at: Date()) self.persistState() self.flushOnWork(completion: nil) } } /// Resume after `optOut()` — or, with `requireConsent`, the user's /// consent: only from here on is the device id stored and anything sent. public func optIn() { guard isEnabled else { return } work.async { let wasPending = self.pending let wasOptedOut = self.state.optedOut if !wasPending && !wasOptedOut { return } let fresh = !self.onDisk let now = Date() self.state.optedOut = false if self.options.requireConsent { self.state.consent = true } if fresh { self.state.installedAt = now } self.persistState() // Consent on a fresh install: from here on it is the first start. if fresh { self.enqueueNow("install", props: nil, userId: nil, at: now) } if wasOptedOut { self.enqueueNow("opt_in", props: nil, userId: nil, at: now) } if wasPending && self.options.trackAppOpen { self.enqueueNow("app_open", props: nil, userId: nil, at: now) } } } /// Whether the SDK collects right now: not opted out and, with /// `requireConsent`, consented. public var isCollecting: Bool { sync { !pending && !state.optedOut } } /// `requireConsent` and no `optIn()` yet (or consent withdrawn). On the work queue. private var pending: Bool { options.requireConsent && !state.consent } /// The install's id: made on the first start, kept across logouts. public var deviceId: String { sync { state.deviceId } } public var isOptedOut: Bool { sync { state.optedOut } } // MARK: - Sending /// Send everything queued now. Safe to call often; concurrent calls share one send. public func flush(completion: (() -> Void)? = nil) { guard isEnabled else { completion?(); return } work.async { self.flushOnWork(completion: completion) } } /// Stop timers (tests, previews). Queued events stay on disk. public func close() { work.async { self.closed = true self.timer?.cancel() self.timer = nil self.timerDueAt = nil } } // MARK: - Internal: queue private func enqueue(_ event: String, props: [String: Any]?, userId: String?) { guard isEnabled else { return } work.async { if self.pending { return } if self.state.optedOut && event != "opt_in" && event != "opt_out" { return } self.enqueueNow(event, props: props, userId: userId, at: Date()) } } /// On the work queue. private func enqueueNow(_ event: String, props: [String: Any]?, userId: String?, at: Date) { var q = QueuedEvent(eventId: UUID().uuidString.lowercased(), event: event, ts: Viewthrough.iso.string(from: at)) if let uid = userId ?? state.userId { q.userId = uid } if let p = props { let clean = p.values.first is PropValue ? p.compactMapValues { $0 as? PropValue } : Viewthrough.cleanProps(p) if !clean.isEmpty { q.props = clean } } events.append(q) let dropped = max(0, events.count - options.maxQueue) if dropped > 0 { events.removeFirst(dropped) Viewthrough.warn("queue full (\(options.maxQueue)), dropped \(dropped) oldest event(s)") } persistQueue() debugLog("queued \(event) (\(events.count) waiting)") if events.count >= options.flushAt { schedule(0) } else { schedule(options.flushInterval) } } /// On the work queue. An earlier timer wins; a shorter one replaces it. private func schedule(_ delay: TimeInterval) { if stopped || closed || events.isEmpty { return } let now = Date() let wait = max(delay, nextAllowedAt.timeIntervalSince(now)) if let due = timerDueAt, timer != nil { if wait >= due.timeIntervalSince(now) { return } timer?.cancel() } let item = DispatchWorkItem { [weak self] in guard let self = self else { return } self.timer = nil self.timerDueAt = nil self.flushOnWork(completion: nil) } timer = item timerDueAt = now.addingTimeInterval(wait) work.asyncAfter(deadline: .now() + max(0, wait), execute: item) } /// On the work queue. private func flushOnWork(completion: (() -> Void)?) { if let c = completion { flushCompletions.append(c) } if flushing { return } flushing = true drain() } /// On the work queue. Sends the oldest batch, then decides from the status. private func drain() { guard !events.isEmpty, !stopped else { return finishFlush() } let now = Date() if now < nextAllowedAt { schedule(nextAllowedAt.timeIntervalSince(now)) return finishFlush() } let batch = Array(events.prefix(Viewthrough.serverMaxBatch)) send(batch) { [weak self] status in guard let self = self else { return } self.work.async { self.handle(status: status, batch: batch) } } } /// On the work queue. private func handle(status: Int?, batch: [QueuedEvent]) { switch Viewthrough.outcome(for: status) { case .sent: remove(batch) attempt = 0 debugLog("sent \(batch.count) event(s)") drain() case .drop: remove(batch) Viewthrough.warn("server rejected \(batch.count) event(s) with HTTP \(status ?? 0); dropped") drain() case .stop: stopped = true Viewthrough.warn("HTTP \(status ?? 0): the SDK key is unknown or revoked — events stay queued until the next start") finishFlush() case .retry: attempt += 1 let wait = Viewthrough.backoff(attempt: attempt) nextAllowedAt = Date().addingTimeInterval(wait) debugLog("send failed (\(status.map(String.init) ?? "network")), retry in \(Int(wait)) s") schedule(wait) finishFlush() } } private func remove(_ batch: [QueuedEvent]) { let ids = Set(batch.map { $0.eventId }) events.removeAll { ids.contains($0.eventId) } persistQueue() } private func finishFlush() { flushing = false let done = flushCompletions flushCompletions = [] for c in done { c() } } enum Outcome { case sent, drop, stop, retry } /// 2xx sent · 400/413 drop (a retry won't fix it) · 401/403 stop (key) · else retry. static func outcome(for status: Int?) -> Outcome { guard let s = status else { return .retry } if s == 202 || s == 200 { return .sent } if s == 401 || s == 403 { return .stop } if s == 429 || s >= 500 { return .retry } if s >= 400 { return .drop } return .retry } /// 1 s, 2 s, 4 s … capped at five minutes. static func backoff(attempt: Int) -> TimeInterval { min(300, pow(2, Double(max(0, attempt - 1)))) } private func send(_ batch: [QueuedEvent], completion: @escaping (Int?) -> Void) { var body: [String: Any] = [ "device_id": state.deviceId, "platform": options.platform, "sdk": ["name": Viewthrough.sdkName, "version": Viewthrough.sdkVersion], "sent_at": Viewthrough.iso.string(from: Date()), "events": batch.map { $0.dictionary }, ] if let u = state.userId { body["user_id"] = u } if let v = options.appVersion { body["app_version"] = v } if let v = options.osVersion { body["os_version"] = v } if let v = options.locale { body["locale"] = v } guard let data = try? JSONSerialization.data(withJSONObject: body) else { Viewthrough.warn("could not encode a batch; dropped") return completion(400) } var request = URLRequest(url: options.endpoint) request.httpMethod = "POST" request.timeoutInterval = 15 request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") request.httpBody = data options.session.dataTask(with: request) { _, response, _ in completion((response as? HTTPURLResponse)?.statusCode) }.resume() } // MARK: - Internal: persistence private func persistState() { // Before consent on a fresh install nothing touches the device. if !onDisk && pending { return } onDisk = true options.userDefaults.set(state.json, forKey: "\(namespace):state") } private func persistQueue() { let k = "\(namespace):queue" if events.isEmpty { options.userDefaults.removeObject(forKey: k) } else { options.userDefaults.set(QueuedEvent.json(events), forKey: k) } } // MARK: - Internal: lifecycle /// Going to the background is the moment a batch is most likely lost; /// send it while iOS still grants a few seconds. private func installLifecycleHooks() { #if canImport(UIKit) && !os(watchOS) let names = [UIApplication.didEnterBackgroundNotification, UIApplication.willTerminateNotification] for name in names { observers.append(NotificationCenter.default.addObserver(forName: name, object: nil, queue: nil) { [weak self] _ in self?.flushInBackground() }) } #endif } #if canImport(UIKit) && !os(watchOS) private func flushInBackground() { guard let app = Viewthrough.application() else { return flush() } final class Box { var id: UIBackgroundTaskIdentifier = .invalid } let box = Box() box.id = app.beginBackgroundTask { if box.id != .invalid { app.endBackgroundTask(box.id); box.id = .invalid } } flush { DispatchQueue.main.async { if box.id != .invalid { app.endBackgroundTask(box.id); box.id = .invalid } } } } /// `UIApplication.shared` by selector, so the file also compiles in /// targets that forbid application APIs (extensions); there it is nil. private static func application() -> UIApplication? { let selector = NSSelectorFromString("sharedApplication") guard UIApplication.responds(to: selector) else { return nil } return UIApplication.perform(selector)?.takeUnretainedValue() as? UIApplication } #endif // MARK: - Internal: helpers private func sync(_ body: () -> T) -> T { if DispatchQueue.getSpecific(key: workKey) != nil { return body() } return work.sync(execute: body) } private func merge(_ props: [String: Any], _ named: [String: String?]) -> [String: Any] { var out = props for (k, v) in named { if let v = v { out[k] = v } } return out } private func debugLog(_ message: String) { if options.debug { print("[viewthrough] \(message)") } } static func warn(_ message: String) { print("[viewthrough] \(message)") } static let iso: ISO8601DateFormatter = { let f = ISO8601DateFormatter() f.formatOptions = [.withInternetDateTime, .withFractionalSeconds] f.timeZone = TimeZone(identifier: "UTC") return f }() /// Strings cut to 256, numbers and booleans as they are, everything else /// dropped. Keys the server would refuse are dropped too — it rejects the /// WHOLE batch (install included) over one bad key, so better one warning /// here than a lost install. static func cleanProps(_ props: [String: Any]) -> [String: PropValue] { var out: [String: PropValue] = [:] for (k, v) in props { guard isValidPropKey(k) else { warnOnce(aboutKey: k); continue } if let p = PropValue(any: v) { out[k] = p } } return out } /// `^[A-Za-z0-9_]{1,64}$`, as in the server's PROP_KEY_RE. static func isValidPropKey(_ key: String) -> Bool { !key.isEmpty && key.count <= 64 && key.allSatisfy { propKeyAllowed.contains($0) } } private static let propKeyAllowed = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") private static let warnedKeysLock = NSLock() private static var warnedKeys = Set() private static func warnOnce(aboutKey key: String) { warnedKeysLock.lock() let first = warnedKeys.insert(key).inserted warnedKeysLock.unlock() if first { warn("prop key \"\(key.prefix(80))\" ignored: letters, digits, _ only (max 64)") } } static func bundleVersion() -> String? { guard let v = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String else { return nil } return isVersion(v) ? v : nil } static func systemVersion() -> String? { let v = ProcessInfo.processInfo.operatingSystemVersion return v.patchVersion == 0 ? "\(v.majorVersion).\(v.minorVersion)" : "\(v.majorVersion).\(v.minorVersion).\(v.patchVersion)" } static func preferredLocale() -> String? { let raw = Locale.preferredLanguages.first ?? Locale.current.identifier let tag = raw.split(separator: "@").first.map(String.init)?.replacingOccurrences(of: "_", with: "-") ?? raw let parts = tag.split(separator: "-") guard let first = parts.first, (2...3).contains(first.count), first.allSatisfy({ $0.isLetter }) else { return nil } guard parts.dropFirst().allSatisfy({ (2...8).contains($0.count) && $0.allSatisfy { $0.isLetter || $0.isNumber } }) else { return nil } return tag.count <= 16 ? tag : String(first) } static func defaultPlatform() -> String { #if os(iOS) || targetEnvironment(macCatalyst) return "ios" #else return "unknown" #endif } static func isVersion(_ v: String) -> Bool { let allowed = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.+-") return !v.isEmpty && v.count <= 32 && v.allSatisfy { allowed.contains($0) } } } // MARK: - Values on the wire and on disk /// A prop value: flat, as the server takes it. enum PropValue { case string(String) case int(Int) case double(Double) case bool(Bool) init?(any: Any) { if let s = any as? String { self = .string(String(s.prefix(256))) return } if let n = any as? NSNumber { if CFGetTypeID(n) == CFBooleanGetTypeID() { self = .bool(n.boolValue) return } let d = n.doubleValue guard d.isFinite else { return nil } if d == d.rounded(), abs(d) < 9_007_199_254_740_992 { self = .int(n.intValue) } else { self = .double(d) } return } return nil } var any: Any { switch self { case .string(let s): return s case .int(let i): return i case .double(let d): return d case .bool(let b): return b } } } /// What goes over the wire, one per event. Same field names as the JS SDK, /// so a queue written by either reads the same. struct QueuedEvent { var eventId: String var event: String var ts: String var userId: String? var props: [String: PropValue]? var dictionary: [String: Any] { var d: [String: Any] = ["event_id": eventId, "event": event, "ts": ts] if let u = userId { d["user_id"] = u } if let p = props, !p.isEmpty { d["props"] = p.mapValues { $0.any } } return d } init(eventId: String, event: String, ts: String) { self.eventId = eventId self.event = event self.ts = ts } init?(dictionary d: [String: Any]) { guard let id = d["event_id"] as? String, let e = d["event"] as? String else { return nil } self.eventId = id self.event = e self.ts = d["ts"] as? String ?? Viewthrough.iso.string(from: Date()) self.userId = d["user_id"] as? String if let p = d["props"] as? [String: Any] { let clean = Viewthrough.cleanProps(p) self.props = clean.isEmpty ? nil : clean } } static func json(_ events: [QueuedEvent]) -> String { let data = (try? JSONSerialization.data(withJSONObject: events.map { $0.dictionary })) ?? Data("[]".utf8) return String(decoding: data, as: UTF8.self) } /// Defensive: a broken file yields an empty queue, never a crash. static func loadQueue(from defaults: UserDefaults, key: String) -> [QueuedEvent] { guard let raw = defaults.string(forKey: key), let arr = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [[String: Any]] else { return [] } return arr.compactMap(QueuedEvent.init(dictionary:)) } } /// Device id, user id, opt-out — what survives a restart. struct Persisted { var deviceId: String var userId: String? var optedOut: Bool = false var installedAt: Date? /// Only meaningful with `requireConsent`: the user agreed via `optIn()`. var consent: Bool = false init(deviceId: String, installedAt: Date?) { self.deviceId = deviceId self.installedAt = installedAt } var json: String { var d: [String: Any] = ["device_id": deviceId, "opted_out": optedOut] if consent { d["consent"] = true } if let u = userId { d["user_id"] = u } if let i = installedAt { d["installed_at"] = Viewthrough.iso.string(from: i) } let data = (try? JSONSerialization.data(withJSONObject: d)) ?? Data("{}".utf8) return String(decoding: data, as: UTF8.self) } static func load(from defaults: UserDefaults, key: String) -> Persisted? { guard let raw = defaults.string(forKey: key), let d = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any], let id = d["device_id"] as? String, id.count >= 8 else { return nil } var p = Persisted(deviceId: id, installedAt: (d["installed_at"] as? String).flatMap(Viewthrough.iso.date(from:))) p.userId = d["user_id"] as? String p.optedOut = (d["opted_out"] as? Bool) ?? false p.consent = (d["consent"] as? Bool) ?? false return p } }