NixtrailTelemetry Client documentation
Package URL

iOS SDK 0.10.5

Integrate NixtrailTelemetry

iOS, Android core, and Android Compose share version 0.10.5. Behavior is unchanged from iOS 0.10.4. Shared release notes.

A client-focused guide for adding installation, session, navigation, engagement, and diagnostic telemetry to an iOS or iPadOS app.

Platforms
iOS and iPadOS 18+
Language
Swift 6
Endpoint
https://api.nixtrail.com
Package
NixtrailTelemetry

Step 1

Install the package

  1. In Xcode, choose File > Add Package Dependencies.
  2. Enter https://sdk.nixtrail.com/NixtrailTelemetry.git.
  3. Select version 0.10.5.
  4. Add the NixtrailTelemetry product to the application target.
Package.swift
.package(
  url: "https://sdk.nixtrail.com/NixtrailTelemetry.git",
  exact: "0.10.5"
)

Step 2

Configure the SDK once

Start telemetry as early as possible during app launch. Nixtrail automatically routes Apple development-signed builds to development, TestFlight builds to staging, and App Store builds to production.

SwiftUI

MyApp.swift
import NixtrailTelemetry
import SwiftUI

@main
struct MyApp: App {
  init() {
    Telemetry.start(TelemetryConfiguration(
      appID: "<APP_UUID>"
    ))
  }

  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

UIKit

AppDelegate.swift
import NixtrailTelemetry
import UIKit

@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
  func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [
      UIApplication.LaunchOptionsKey: Any
    ]? = nil
  ) -> Bool {
    Telemetry.start(TelemetryConfiguration(
      appID: "<APP_UUID>"
    ))
    return true
  }
}

Lifecycle observation is automatic in both frameworks. UIKit apps do not forward AppDelegate or SceneDelegate callbacks to Nixtrail.

Use the resolved environment in your app

APIEnvironment.swift
let environment = await TelemetryEnvironment.current()

let apiURL = switch environment {
case .development: URL(string: "https://dev-api.example.com")!
case .staging: URL(string: "https://stage-api.example.com")!
case .production: URL(string: "https://api.example.com")!
case .unknown: throw APIBootstrapError.environmentUnavailable
}

Automatic resolution first checks the signed get-task-allow entitlement, so optimized and custom Xcode configurations resolve to development without relying on DEBUG. Other builds use Apple’s verified StoreKit app transaction: sandbox maps to staging and production maps to production. An unverified result is .unknown rather than an unsafe guess.

Explicit override for unusual builds

CI or Ad Hoc configuration
Telemetry.start(TelemetryConfiguration(
  appID: appID,
  environment: .fixed(.staging)
))

Call Telemetry.start only once. For tests or launch flows that need to await a setup attempt, use await Telemetry.startAndWait(...) and inspect Telemetry.status(). An unavailable environment can still defer completion.

Added in 0.10.3

Retain activity while startup is deferred

If StoreKit cannot provide a verified distribution environment, the SDK starts lifecycle and MetricKit observation and buffers up to 100 capture operations in memory. Custom events, screen navigation/loading/scrolling, lifecycle transitions, and bounded diagnostic reports retain their timestamps and submission order.

Setup retries every 30 seconds. Only one startup attempt runs at a time. When the environment resolves, capture is replayed under the stored collection policy and the resulting events enter the normal disk queue. One capture operation can produce several events.

StatusMeaning
isConfiguredRemains false until environment-scoped setup completes.
environmentRemains .unknown while resolution is unavailable.
bufferedStartupCaptureCountCapture operations waiting in memory; at most 100.
droppedStartupCaptureCountStartup captures dropped for overflow or oversized diagnostic properties; also included in droppedEventCount.
queuedEventCountPersisted events, separate from the startup buffer.
lastErrorDescribes the unresolved environment and in-memory buffering.

On recovery, sdk.environment.resolved reports startup_delay_ms, buffered_capture_count, dropped_capture_count, and environment when automatic SDK health events are enabled. Normal collection policy and queue limits still apply.

Disabling collection clears buffered startup capture; starting disabled also clears activity submitted before start. Re-enabling cannot recover that activity. Existing persisted queue behavior is unchanged. Screenshot replay starts after setup while foregrounded and cannot reconstruct the deferred period.

Upgrade: resolve exact version 0.10.5 and rebuild each app. No server change or new instrumentation is needed. Verified environment routing and the environment's App Attest or enrollment-key requirements remain unchanged.

Validated with 93 macOS tests, 102 iOS simulator tests, both sample-app Release builds, and the iOS 18 minimum-target build. Failure injection covers recovery, timestamps, diagnostic deduplication, consent, overflow, stored policy, automatic retry, and concurrent startup.

Step 3

Choose production enrollment security

Production apps can use Apple App Attest or a client enrollment key. Development and staging environments do not require either mechanism.

Apple App Attest

Recommended when supported by the product. Enable the App Attest capability on the application target and give the Nixtrail administrator the exact bundle ID and Team ID.

Enrollment key

Pass the key created in the dashboard. It is used only to register the installation; later requests use an installation-scoped credential.

Enrollment key configuration
Telemetry.start(TelemetryConfiguration(
  appID: appID,
  enrollmentKey: productionEnrollmentKey
))

Default behavior

Data collected automatically

The defaults are deliberately bounded. They describe app lifecycle, active use, runtime health, and failures without recording every interaction.

EventMeaning
app.installedFirst SDK launch after installation.
app.first_openedFirst open for the installation.
app.openedCold process launch.
app.updatedVersion or build changed.
app.foregroundedApp returned to the foreground.
app.backgroundedApp entered the background.
app.closedBest-effort iOS termination notification.
app.termination.abnormalPrevious process ended without a clean marker; this is an unconfirmed signal.
session.startedNew foreground activity period.
session.timeoutBackground inactivity crossed the configured timeout.
session.endedSession totals and terminal reason.
app.cold_start / app.warm_startCold launch or foreground return reached the active state.
network.online / network.offline / network.changedNetwork path availability or category changed.
locale.changed / timezone.changedLocale or time-zone settings changed.
theme.changed / orientation.changedAppearance or physical orientation category changed.
power.low_mode.changedLow Power Mode changed.
battery.changed / battery.lowFive-percent battery bucket or charging state changed, or battery crossed 20% unplugged.
memory.warning / thermal.warningiOS reported memory or thermal pressure.
performance.sampleMetricKit delivered a daily aggregate for CPU, memory, disk, network, launch, responsiveness, and exits.
app.crashedConfirmed MetricKit crash diagnostic.
app.hang.detectedMetricKit hang diagnostic.
app.cpu_exception.detectedMetricKit CPU exception diagnostic.
app.disk_write_exception.detected / app.launch.slowMetricKit disk-write or slow-launch diagnostic.
sdk.started / sdk.stoppedNixtrail SDK process lifecycle.
queue.dropped / event.failedBounded queue pressure or server rejection.

Background and locked-screen time does not count toward active app duration. MetricKit diagnostics arrive asynchronously, often after a later launch.

Engagement

Track screens and scrolling

Use stable product names such as home, checkout, or library.album_detail. Never include user data or database IDs in a screen name.

ArticleView.swift
ScrollView {
  ArticleContent(article: article)
}
.telemetryScrollTracking("article")
.telemetryScreen(
  "article",
  properties: ["source": .string("featured")]
)
.task {
  await article.load()
  Telemetry.screenReady("article")
}

The SDK emits one completed screen.view event when the screen ends. It can include foreground duration, previous and next screen, load duration, maximum scroll depth, reached-end state, scroll duration, and interaction count.

UIKit or custom navigation

UIViewController callbacks
override func viewDidAppear(_ animated: Bool) {
  super.viewDidAppear(animated)
  Telemetry.screenView("checkout")
}

override func viewDidDisappear(_ animated: Bool) {
  Telemetry.endScreenView("checkout")
  super.viewDidDisappear(animated)
}

func didFinishLoadingCheckout() {
  Telemetry.screenReady("checkout")
}

Nixtrail serializes these client calls in submission order, so rapid view-controller callbacks cannot overtake one another. Screen tracking does not swizzle UIKit classes; opt-in replay installs a guarded touch-observation hook.

Added in 0.10.0

Crash context and diagnostics

The hosted Nixtrail API supports SDK 0.10.5. Self-hosted servers must accept per-event context before clients update; older servers reject that field.

Instrument visible screens with .telemetryScreen or Telemetry.screenView. The SDK now persists screen.entered immediately; completed screen.view spans still provide durations. It cannot infer semantic screens or business actions automatically.

Track meaningful actions through your existing analytics layer. For an operation that may terminate the process, await Telemetry.trackAndWait before starting it. Keep essential breadcrumb details as small scalar fields: nested objects and arrays are excluded, and details are bounded to 512 encoded bytes. Awaiting persistence does not guarantee storage when the device reports an I/O error; inspect Telemetry.status().

Up to 32 breadcrumbs for each of 16 recent session contexts are retained locally for up to seven days. Reports carry at most three candidate contexts with eight breadcrumbs each, within a 14,000-byte budget. Current event policy is checked again before upload.

MetricKit reports use their diagnostic interval, which may be a single instant, and preserve preceding activity without including later actions. Their authoritative session_id is empty. Candidate sessions are explicitly unconfirmed; the new launch is excluded from crash candidates.

Crash, hang, CPU, disk-write, and launch reports appear under Crash and diagnostic reports on the installation page. Original app/build metadata and up to 24 stack frames are retained. Keep matching archives and dSYMs for symbolication. Installation-scoped IDs suppress retries without merging reports from different devices.

Session replay remains opt-in and separate from breadcrumbs. This release does not reconstruct previously missing history.

The preceding 0.10.0 crash-context release was validated on a physical iPhone 13 Pro: actual SIGTRAP, relaunch, real MetricKit delivery, prior screen/action details, 19 stack frames, and desktop/mobile dashboard inspection. The test used a signed Release build with development enrollment.

Fixed in 0.10.2

Nested diagnostic stacks and stable fingerprints

SDK 0.10.1 applied a 32-container JSON limit to MetricKit's recursive stack trees. A single thread with 15 nested frames could discard every thread's stack, and deep reports could receive different fingerprints when JSON keys were reordered.

SDK 0.10.2 fixes both paths with a shared 2 MiB / 256-container diagnostic budget. This accommodates 126 nested frames with the call-stack wrapper. Capture still prioritizes attributed threads and keeps at most 24 frames / 8,000 encoded bytes. The stricter general disk/network JSON guard remains unchanged.

stack_statusMeaning
capturedFrames retained; check stack_truncated for omissions.
unavailableValid JSON contained no usable stack frames.
depth_limit_exceededThe entire tree exceeded the nesting budget.
too_largeThe stack JSON exceeded the byte budget.
invalid_jsonThe stack JSON could not be parsed.

diagnostic_identity_status=canonical confirms sorted-key fingerprinting. raw_depth_limit_exceeded, raw_too_large, or raw_invalid_json identifies raw fallback, which cannot deduplicate changes in key order. Full diagnostic identities exceeding 2 MiB are dropped at submission.

Upgrade: resolve exact version 0.10.5 and rebuild the app. No client instrumentation or server changes are required for this fix. On a test phone, trigger a deliberate crash outside the debugger, relaunch, and inspect the report when MetricKit delivers it: a 21-frame nested thread should report stack_status=captured and diagnostic_identity_status=canonical.

Over-budget trees still reject as a whole. Previously lost stacks cannot be recovered. A deep report fingerprinted as raw bytes by 0.10.1 can receive a different ID if redelivered after upgrading; queued event IDs are preserved.

Validated with 85 macOS tests, 94 iOS simulator tests, both SwiftUI/UIKit lab Release builds, and the iOS 18 minimum-target build. Deep-stack fixtures cover 15, 21, 100, and 126 frames, reordered JSON, persisted redelivery, and utility-thread boundary handling.

App-cooperative capture

Forward standard observations

iOS does not expose a supported global callback for every interaction. Call these standardized helpers from the delegate or component that already handles the action.

Observations.swift
Telemetry.uiInteraction(
  .buttonClicked,
  screen: "checkout",
  accessibilityID: "subscribe"
)
Telemetry.gesture(.swipe, screen: "gallery", direction: "left")
Telemetry.networkRequest(
  method: "GET",
  host: "api.example.com",
  route: "/v1/catalog",
  status: 200,
  duration: 0.184
)
Telemetry.notification(.opened, category: "weekly_summary")
Telemetry.deepLinkOpened(
  scheme: "myapp",
  host: "catalog",
  route: "/item"
)
Telemetry.permission(.granted, permission: "camera")
Telemetry.backgroundTask(
  .finished,
  task: "catalog_refresh",
  duration: 2.4,
  succeeded: true
)

Network and deep-link routes drop query strings and fragments. These helpers never accept bodies, headers, typed text, visible control text, touch coordinates, or complete URLs.

Product telemetry

Add meaningful custom events

Track completed actions and outcomes instead of implementation details or every tap.

CheckoutViewModel.swift
Telemetry.track(
  "checkout.completed",
  properties: [
    "plan": .string("annual"),
    "trial": .bool(false),
    "item_count": .int(3),
    "duration_ms": .int(842)
  ],
  priority: .normal
)

Property values support strings, booleans, integers, doubles, arrays, nested objects, and null. Use stable categories and counts rather than free-form user content.

Added in 0.10.4

Test the real app action

SDK 0.10.4 adds a public test recorder; earlier versions do not include it. Use it to test the real action that calls your existing Analytics.track wrapper, rather than only testing a function that describes which events should be sent:

Swift Testing
import Testing
import NixtrailTelemetry

// Call this helper from a test with your isolated store and receipt fixture:
// assertXPSubmission { store.adopt(receipt) }
// This example expects 25 earned XP without a level change.
@MainActor
func assertXPSubmission(adopt: () -> Void) {
  let recorder = TelemetryTestRecorder()

  Telemetry.withTestRecorder(recorder) {
    #expect(recorder.events.isEmpty)
    adopt()
    #expect(recorder.events.map(\.name) == ["xp.earned"])
    #expect(recorder.events.first?.properties["gained"] == .int(25))
  }
}

No changes to the app's Analytics.track forwarding code are needed. Both Telemetry.track and trackAndWait record before returning. Async actions use try await Telemetry.withTestRecorder(recorder) { try await action() }; await the action's child work before asserting. Intermediate assertions and the occurredAt timestamp help test timing; the SDK cannot know when app work has finished if the app does not expose an awaitable completion.

Each TelemetryRecordedEvent contains name, sanitized properties, priority, and occurredAt. Invalid names are ignored. events returns a thread-safe snapshot. Sequential calls retain their order; concurrent calls are ordered by acquisition of the recorder's lock, not a promised causal order. The default capacity is 256 (configurable from 1 to 1,000); overflow drops new events and increments droppedEventCount. Use a fresh recorder for each test.

Scopes are task-local, so parallel tests do not share a global listener. Nested scopes restore the previous recorder, including on throw. Structured children and Task {} inherit the scope. An escaping child can retain it after the parent closure returns. Task.detached, dispatch queues, and unrelated UI callbacks do not inherit it: establish a scope where they call analytics, or inject an analytics dependency at that boundary. In-process scopes cannot observe a separate app process in an XCUITest.

This is a replacement sink for custom-event submissions, not a delivery observer. Intercepted calls never reach the command queue/runtime; runtime consent, remote policy, sampling, and admission budgets are bypassed. App-level consent guards still run and should be tested both enabled and disabled. Do not enable a recorder in production. Do not start the SDK for these unit tests: startup, automatic/lifecycle events, screen helpers, typed observations, error capture, and flush operations are not intercepted and retain their normal behavior. Use separate integration tests for persistence and server delivery.

Diagnostics

Capture handled errors

CatalogService.swift
do {
  try await catalog.refresh()
} catch {
  Telemetry.capture(
    error: error,
    source: "catalog_refresh",
    properties: [
      "operation": .string("refresh"),
      "retryable": .bool(true)
    ]
  )
}

The SDK records the error type, source, and safe custom properties. Concrete Foundation errors retain domain and code; application-defined metadata getters are not invoked. Include safe scalar codes explicitly for custom errors. It does not send localized error messages or stack traces.

Optional capture

Privacy-filtered session replay

Replay is disabled by default and requires both local opt-in and an enabled environment policy. Either side is a kill switch.

Enable replay
Telemetry.start(TelemetryConfiguration(
  appID: appID,
  sessionReplay: SessionReplayConfiguration(
    isEnabled: true
  )
))

The default profile preserves ordinary labels, navigation, buttons, and imagery so the replay remains useful. UIKit text-entry controls, web views, maps, PDFs, player surfaces, and explicitly sensitive regions are replaced with solid blocks. Mark sensitive SwiftUI or custom-rendered content with .sessionReplayMasked() in SwiftUI or view.nixtrailSessionReplayMasked = true in UIKit. Set maskAllText and/or maskAllImages to true only when an app needs strict whole-frame pixelation.

Defaults are tuned for cost: 540-pixel maximum edge, JPEG quality 0.28, at most one frame per second, and identical-frame suppression. Chunks are compressed, protected on disk while queued, stored separately from PostgreSQL events, and bounded by remote sampling, retention, and per-session byte limits.

Replay is fail-closed. UIKit rendering runs behind an Objective-C exception boundary, image encoding runs away from the main thread with only one frame in flight, and capture disables itself after a rendering failure or memory warning. Touch observation preserves existing event hooks and never presents user-facing error UI.

Hardened in 0.10.1

Host failure isolation

Commands, property processing, event admission, disk queues, responses, and diagnostics have bounded budgets. Blocking storage uses a dedicated utility executor. Uploads are coalesced; setup deadlines and single in-flight framework calls prevent retries from accumulating stalled work.

Overload intentionally drops telemetry. Inspect droppedCommandCount, droppedEventCount, and lastError through Telemetry.status(). Custom error capture retains the error type without invoking application-defined metadata getters; include safe scalar codes explicitly when needed.

Replay stops on persistence failures, serializes uploads, guards late starts, and limits rendering work. A capture taking more than 16 ms disables further capture after the current call returns. UIKit and host drawing code still run on the main thread: the SDK cannot interrupt a stuck renderer, catch every Swift trap, or eliminate memory-exhaustion risk. Screenshot replay remains opt-in.

Validated with 79 macOS tests, 88 iOS simulator tests, failure injection, UI responsiveness checks, and Thread Sanitizer. These checks establish tested behavior, not a universal guarantee of zero host impact.

Privacy

Collection boundaries

Collected when enabled

Lifecycle, sessions, startup, device and connectivity changes, resource signals, MetricKit aggregates and diagnostics, SDK health, semantic observations explicitly forwarded by the app, plus privacy-filtered screen frames and normalized touches when replay is enabled.

Never collected as content

Request bodies, headers, raw view hierarchies, Wi-Fi names, IP addresses, complete URLs, query parameters, or disk free/total capacity. UIKit inputs and configured sensitive replay regions are blocked before upload.

Keys associated with credentials, authentication, and personal contact data are removed by the SDK and rejected by the server. Region is derived from the current locale; it is not precise location and is not guaranteed to match the App Store storefront.

Version 0.10.5 preserves explicitly supplied latitude, longitude, and location properties, including nested coordinate objects. The server accepts these fields. The SDK does not request location permission or collect GPS coordinates automatically. Update older SDK versions before sending coordinates.

Support

Troubleshooting

The package does not resolve
Confirm the URL is exactly https://sdk.nixtrail.com/NixtrailTelemetry.git, then reset package caches in Xcode and resolve version 0.10.5.
No installation appears
Verify the app UUID is non-empty and present in the built app. Remove DEBUG, $(ACTION), or configuration-name gates. Inspect status.isConfigured, status.isEnabled, status.environment, and status.lastError, then check HTTPS connectivity and production enrollment.
Startup remains unconfigured
Inspect environment, lastError, and the startup buffer/drop counters. Automatic resolution retries every 30 seconds. An unknown environment cannot enroll or upload; the buffer is lost if the process exits before recovery.
Production enrollment fails
Confirm the signed bundle ID and Team ID match the production environment, or provide an active enrollment key.
A screen event is not immediate
While setup is deferred, check bufferedStartupCaptureCount and lastError. After setup, screen.entered is persisted immediately; screen.view is emitted when the span completes so its duration and destination are known.
Crash data is delayed
MetricKit controls diagnostic delivery and commonly reports after a later app launch.

Reference

Version compatibility

DocumentationSDKSwiftMinimum OS
0.10.50.10.56iOS/iPadOS 18

This guide describes the public API and server contract shipped in NixtrailTelemetry 0.10.5.

Dashboard result

From events to user stories

The dashboard groups activity by installation and session, then presents screen engagement and chronological actions as readable stories.

Nixtrail installation detail showing sessions, active time, app version, and device context.
Installation and session history in the Nixtrail dashboard.