Integrate an SDK · iOS

iOS SDK

Swift package with core capture/replay and an optional signed-patch product. It writes capsule spec v1 (spec v2 for capsules with WebSocket or native adapter traffic) with sdk.name: bugcapsule-ios, runtime.name: ios, and replays through an XCUITest the CLI launches on a simulator.

Version
0.4.2 (sdkVersion in Sources/BugCapsule/Runtime/Session.swift)
Platforms
iOS 15+ (macOS 12+ only for the package's unit tests)
Language
Swift 6 language mode, strict concurrency, swift-tools 6.0
Products
BugCapsule (app target), BugCapsuleXCTest (UI test target), BugCapsulePatch (optional app target)
Links
zlib (gzip); XCTest for the test product

In 0.4.2, close(timeout:) waits for queued work that preserves the previous run's crash before stopping monitoring. Its timeout bounds the flush only, so closing can take longer while that work finishes.

1. Add the package

In Xcode, add https://github.com/BugCapsule/bug_capsule_ios_sdk.git as a package dependency with exact version 0.4.2. Add BugCapsule to the app target and BugCapsuleXCTest to the UI test target. In a Package.swift:

.package(url: "https://github.com/BugCapsule/bug_capsule_ios_sdk.git", exact: "0.4.2"),

// app target
.product(name: "BugCapsule", package: "bug_capsule_ios_sdk"),
// UI test target
.product(name: "BugCapsuleXCTest", package: "bug_capsule_ios_sdk"),

Optional signed patch product

The published 0.4.2 release exposes BugCapsulePatch from the same Swift package. Add this product to the app target alongside BugCapsule:

.product(name: "BugCapsulePatch", package: "bug_capsule_ios_sdk"),

The release includes the native XCFramework for iOS arm64 and arm64/x86_64 simulators. Import BugCapsulePatch, register typed PatchModule fallbacks, then attach a BugCapsulePatchBinding through BugCapsuleConfig.patchBinding before capture begins. PatchUpdater and HttpPatchTransport provide signed staging and receipts; activation happens at the next launch.

See Signed patches: setup, integration and rollback for the complete flow. Trust roots, application/environment, base build and registered contracts must match the release binary. This product patches registered logic and surfaces; it does not replace arbitrary Swift or Objective-C, change native dependencies, or confer store approval.

2. Connect with your SDK token

i

SDK tokens and the status API are included in these releases. Use the SDK token from your dashboard for a new integration. Existing explicit API URL and ingest key configuration remains supported.

Generate an SDK token in the dashboard (Project Settings › Keys › SDK tokens; it is shown once) and start BugCapsule with it, first thing:

import BugCapsule

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    BugCapsule.start(token: "bcsdk.v1.…")
    return true
}
import BugCapsule
import SwiftUI

@main
struct ShopApp: App {
    init() { BugCapsule.start(token: "bcsdk.v1.…") }   // App.init runs before any view reads UserDefaults
    var body: some Scene { WindowGroup { RootView() } }
}

That is the whole connection setup. The token (bcsdk.v1.…) carries your BugCapsule address and an upload-only credential; it is safe to ship in the app (it cannot read data or change settings) and you can rotate or revoke it in the dashboard. It works the same for hosted and self-hosted BugCapsule. App version and build default to CFBundleShortVersionString / CFBundleVersion, and capture is on (.debug mode in DEBUG builds, .production with sampling otherwise).

start never throws for a bad token: a token that cannot be used (empty, damaged, an ingest or secret key pasted instead, or a newer token version than this SDK understands) logs one [bugcapsule] line that says what to do, and the app runs without uploads.

Check the connection

let status = BugCapsule.status
status.connection.state                  // .connecting, .connected, .offline, .rejected, ...
status.connection.reason                 // e.g. "token_revoked"
status.connection.message                // what to do about it
status.connection.configFetchedAt        // 1st confirmation: configuration fetched
status.connection.firstEventAcceptedAt   // 2nd confirmation: first event received …
status.connection.firstCapsuleAcceptedAt // … or first Capsule received
status.instrumentation.missing           // e.g. ["network", "navigation", "app_state"]
connection.stateMeaning
.notConfiguredNot started, or no token / backend (capsules are only saved on the device)
.invalidToken, .unsupportedTokenVersionThe token cannot be used; message says why
.connectingWaiting for the first configuration fetch
.connectedThe configuration was fetched in this run
.offlineBugCapsule could not be reached (network error, timeout, server error). Data waits in the outbox and is retried
.rejectedThe token was refused (reason: token_revoked, token_expired, token_unknown, …; message: what to do). Capture and uploads are off for this run
.disabledenabled: false, or capture is turned off for the project

connection also has source (.token / .backend) and apiURL. The two confirmations are separate, as in the dashboard's onboarding and SDK token list: Configuration fetched proves address, token and network; First event or Capsule received proves captured data reaches your project. Connected is not the same as fully instrumented: that is instrumentation, and the next step.

3. Add the progressive adapters

Replay-grade capsules need network, navigation and app state, which you add as integrations. Each one you skip is listed in BugCapsule.status.instrumentation.missing.

Step (missing entry)Gives replayAdd
networkRecorded responses served as fixturesBugCapsuleURLSession in integrations and BugCapsule.instrument(_:) or instrumentSharedSession() (step 4)
navigationRoute events and the route restoredBugCapsuleNavigation.shared, once it has seen a navigation controller or a route (step 5)
app_stateStorage and state restored at startBugCapsuleUserDefaults, or state registered with BugCapsule.registerState (step 7)
import BugCapsule

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    BugCapsule.start(
        BugCapsuleConfig(
            token: "bcsdk.v1.…",
            mode: .qa,  // default: .debug in DEBUG builds, .production otherwise
            redactKeys: ["loyaltyId"]),
        integrations: [
            BugCapsuleURLSession(rules: [
                EndpointRule("POST", "/api/checkout", ignoreBodyFields: ["timestamp", "nonce"]),
            ]),
            BugCapsuleUserDefaults(keys: ["cart_cache"], prefixes: ["settings."]),
            BugCapsuleNavigation.shared,
            BugCapsuleStateIntegration.shared,
        ])
    return true
}
import BugCapsule
import SwiftUI

@main
struct ShopApp: App {
    init() {
        // App.init runs before any view reads UserDefaults.
        BugCapsule.start(
            BugCapsuleConfig(token: "bcsdk.v1.…", mode: .qa),
            integrations: [BugCapsuleURLSession(), BugCapsuleUserDefaults(prefixes: ["shop."]),
                           BugCapsuleNavigation.shared, BugCapsuleStateIntegration.shared])
    }
    var body: some Scene { WindowGroup { RootView() } }
}

start must run before app code reads UserDefaults: in replay it fetches the capsule and restores the checkpoint synchronously there. It is @MainActor; a second call is ignored with a warning; if storage or setup fails the app runs without capture. Besides BugCapsule.status: BugCapsule.isStarted, isRecording, isReplaying, mode, session.

Self-hosted or existing setups (advanced)

A self-hosted BugCapsule issues tokens that carry its own address, so the one-liner works there too. You can also configure the address and ingest key yourself, as before; existing apps keep working:

BugCapsule.start(BugCapsuleConfig(
    backend: BugCapsuleBackendConfig(url: "https://api.bugcapsule.com",
                                     ingestKey: "bci_...")))   // never the bcs_ secret key

An explicit backend wins over token (the SDK logs that the token was ignored). BugCapsuleConnectionToken.parse(_:) and BugCapsuleBackendConfig(token:) turn a token into this configuration offline, for apps that want to validate one themselves.

Choosing the mode

Resolution order: config.mode → Info.plist key BugCapsuleMode → environment BUGCAPSULE_MODE → .debug under #if DEBUG, else .production. Only sampling depends on the mode: debug and QA always record, production records with probability min(productionSampleRate, remote sampleRate).

4. Instrument networking

let config = URLSessionConfiguration.default
BugCapsule.instrument(config)                 // inserts BugCapsuleURLProtocol first
let session = URLSession(configuration: config)

// Alamofire: same configuration, Session(configuration: config)
// URLSession.shared: BugCapsule.instrumentSharedSession()  (URLProtocol.registerClass, opt-in)
!

instrument alone records nothing. The protocol only activates when a BugCapsuleURLSession instance is in start(integrations:). Add it even if you use the defaults: BugCapsuleURLSession().

BugCapsuleURLSession(…)DefaultNotes
rules[]EndpointRule(method, path, ignoreQuery:, ignoreBodyFields:, matchBodyFields:); :name segments, trailing *
ignoreQuery_ ts timestamp nonce cachebust
ignoreBodyFields[]
maxBinaryBytes, maxKeyBodyBytes64 KiB
maxBodyWait30 s
excludenil(URLRequest) -> Bool: record only method, URL, status, timing

Redirects are followed inside the SDK protocol (the final response is recorded and served; app redirect delegates are not consulted). httpBodyStream bodies are keyed without a body hash and not recorded. Stream tasks are not captured. WebSocket tasks created directly are not captured either; sockets opened through BugCapsuleWebSocket are (below).

WebSockets

i

Available from 0.4.1-beta.3, together with native adapters. Capsules with WebSocket or adapter traffic are written as capsule spec v2, which older CLIs reject: update the CLI everywhere it runs, CI included, before you turn these on. Other capsules stay v1.

URLSessionWebSocketTask can't be intercepted, so open sockets through BugCapsuleWebSocket (the same calls) and add BugCapsuleWebSockets() to the integrations:

BugCapsule.start(config, integrations: [BugCapsuleURLSession(), BugCapsuleWebSockets()])

let socket = BugCapsuleWebSocket(session: .shared, url: URL(string: "wss://quotes.example.com/v1/stream")!)
socket.delegate = self              // didOpenWithProtocol / didCloseWith / didCompleteWithError
socket.resume()
try await socket.send(.string(#"{"op":"subscribe","symbol":"ACME"}"#))
let message = try await socket.receive()
socket.cancel(with: .normalClosure, reason: nil)

Other SDKs (native adapters)

Results of third-party SDKs (location, Firebase, payments) are recorded through an adapter that implements BugCapsuleNativeAdapter and routes its calls and streams through BugCapsuleNativeBridge. Install it with BugCapsuleNativeIntegration(adapter). In replay the SDK is never called; the recorded answers come back at their recorded times.

final class LocationAdapter: BugCapsuleNativeAdapter, @unchecked Sendable {
    let descriptor = BugCapsuleAdapterDescriptor(
        dependencyId: "location", adapter: "acme.location", adapterVersion: "1.0.0", schema: 1,
        operations: ["location.current", "location.updates"],
        tested: [BugCapsuleTestedPackage("AcmeLocationSDK", "2.1")])

    private let sdk: AcmeLocationSDK
    private var bridge: BugCapsuleNativeBridge?
    init(sdk: AcmeLocationSDK) { self.sdk = sdk }
    func attach(_ bridge: BugCapsuleNativeBridge) { self.bridge = bridge }

    func current() async throws -> Any? {
        try await bridge!.call("location.current") { try await self.sdk.currentLocation().json }
    }
}

BugCapsule.start(config, integrations: [BugCapsuleURLSession(), BugCapsuleNativeIntegration(locationAdapter)])

Check your adapter offline with BugCapsuleAdapterConformance.run: capture, capsule, replay, and no divergences.

func testMyAdapterIsConformant() async throws {
    let report = try await BugCapsuleAdapterConformance.run(
        makeAdapter: { replaying in MyAdapter(sdk: replaying ? FailingSDK() : FakeSDK()) }
    ) { adapter, log in
        log.append("value: \(try await (adapter as! MyAdapter).get("carts/1"))")
    }
    XCTAssertTrue(report.isClean, report.problems.joined(separator: "\n"))
}

Replaying a capsule with WebSocket or adapter traffic needs the same adapter installed with a supported schema; otherwise the attempt ends INCOMPATIBLE (dependency.unsupported). Bounds shared by every adapter: 64 KiB per payload, 1 MiB of payloads per recorder window, 32 captured connections and subscriptions at a time. Your project's capture settings can switch off a single adapter without touching HTTP capture. Divergences and reason codes: interaction divergences.

5. Name actions and track text

button.addAction(BugCapsule.uiAction("cart.checkout") { [weak self] in self?.checkout() },
                 for: .touchUpInside)
BugCapsule.trackText("cart.coupon", field: couponField)   // isSecureTextEntry is always redacted
BugCapsule.observe(navigationController)                   // route events (set your own delegate first)
Button("Checkout", action: BugCapsule.action("cart.checkout") { model.checkout() })
TextField("Coupon", text: BugCapsule.trackedText("cart.coupon", $model.coupon))
SecureField("PIN", text: BugCapsule.trackedText("login.pin", $pin, sensitive: true))
CartView().bugCapsuleRoute("/cart")

Semantic replay invokes these actions by id and restores tracked text by id. Lower-level API: action(_:payloadHandler:), registerAction(_:handler:), recordAction(_:payload:), trackText(_:setter:) + textChanged(_:value:sensitive:), and View.bugCapsuleAction(_:perform:) (registers a handler only; pair it with recordAction).

!

iOS does not replay touches. input.pointer.replay is unsupported: XCUITest taps can't be timed to recorded milliseconds. Touches are only captured, and only if you opt in with BugCapsuleWindow or BugCapsule.recordTouches(_:in:). A capsule with pointer input and no semantic action gets the material pointer.unsupported divergence. Name every action that matters.

6. Assert what "broken" means

BugCapsule.check("cart_total_non_negative", total >= 0, "total \(total)")
BugCapsule.fail("checkout_stuck", "spinner after 10s")
BugCapsule.report(error: error)            // errors the app caught (honours config.ignoreError)
BugCapsule.report(exception: exception)
BugCapsule.log("legacy cart migrated", level: "warn")

A failure writes a capsule automatically after a 300 ms settle delay, at most 3 per session, one per signature, and queues it for upload.

Failure-capture boundaries

CapturedNot captured (never claimed)
check, fail, report(error:), report(exception:); uncaught NSExceptions via a chained NSSetUncaughtExceptionHandler (previous handler always called; capsule written synchronously, uploaded next launch, carries crash.persisted) Swift traps (fatalError, precondition, force unwrap of nil, index out of range, overflow, try!), POSIX signals, C++ exceptions, OOM/jetsam, watchdog kills, force-quit. Call check or report(error:) before code that would trap.

Requests in flight when the crash capsule is written are recorded with "pending": true; replay holds them open.

7. State, storage and determinism

// App state in checkpoints, restored in replay. Register before the replay's first input.
// (pattern from Examples/Demo/BugCapsuleDemo/AppDelegate.swift)
BugCapsule.registerState(
    "app.session",
    snapshot: { [unowned self] in
        ["lastOrderId": lastOrderId.map { .string($0) } ?? .null,
         "appliedCoupon": appliedCoupon.map { .string($0) } ?? .null]
    },
    restore: { [unowned self] json in
        lastOrderId = json["lastOrderId"]?.stringValue
        appliedCoupon = json["appliedCoupon"]?.stringValue
    })
BugCapsule.stateChanged("app.session", value: appliedCoupon.map { .string($0) })   // diagnostic `state` event

// UserDefaults: allowlist only (nothing else is read)
BugCapsuleUserDefaults(keys: ["cart_cache"], prefixes: ["settings."],
                       denyPrefixes: ["bugcapsule.", "com.apple.", "Apple", "NS"], suiteName: nil)

// Navigation restore from periodic checkpoints needs your restorer (yourRouter is app code)
BugCapsuleNavigation.shared.restorer = { route, backStack in try yourRouter.reset(to: backStack + [route]) }
BugCapsuleNavigation.shared.setRoute("/cart")                 // explicit routes

// Determinism: only these are virtualized
let now = BugCapsule.now()                                  // recorded wall clock in replay
let n = BugCapsule.random.nextInt(100)                      // seeded per session

UserDefaults types: bool, int, double, string, stringArray, data (base64), date (epoch ms). Keychain, Core Data, files and SQLite are not captured; write a BugCapsuleIntegration (name, snapshot, restore, describeEligibility).

8. Add the replay test

import BugCapsuleXCTest

final class BugCapsuleReplayTests: BugCapsuleReplayTestCase {
    @MainActor func testReplay() throws { try runBugCapsuleReplay() }
}

runBugCapsuleReplay(timeout: 900) throws XCTSkip when the CLI didn't start the test, so it is safe in a normal test run. Override makeApplication() to customize the XCUIApplication.

9. Embed the git SHA

<key>BugCapsuleGitSHA</key><string>$(BUGCAPSULE_GIT_SHA)</string>
<key>BugCapsuleGitDirty</key><string>$(BUGCAPSULE_GIT_DIRTY)</string>

The CLI passes both build settings when it builds. For every other build that can capture (QA, CI and App Store release builds alike), pass BUGCAPSULE_GIT_SHA=$(git rev-parse HEAD) to xcodebuild. Keep BUGCAPSULE_MODE=qa to the QA configuration. Unexpanded $(…) values count as unset; without a SHA capsules are partial (build.gitSha) and bugcapsule run can't pin the commit.

i

Privacy manifest. The package ships no PrivacyInfo.xcprivacy. It uses UserDefaults, file timestamps and ProcessInfo.systemUptime, which Apple lists as required-reason APIs, so declare them in your app's privacy manifest before App Store submission.

Configuration reference

BugCapsuleConfig(…): every property is a var with a default.

PropertyDefaultNotes
appVersion, appBuild, appId, appNamebundle valuesCFBundleShortVersionString, CFBundleVersion, bundle id, CFBundleName
flavornil
modenil → see above.debug, .qa, .production
enabledtrueLocal master switch
tokennilThe SDK token (bcsdk.v1.…) from the dashboard: all a connection needs. Same as BugCapsule.start(token:)
backendnilBugCapsuleBackendConfig(url:ingestKey:): the advanced alternative to token, and wins over it
gitSha, gitDirtyInfo.plistBugCapsuleGitSHA, BugCapsuleGitDirty
stateSchemaVersion1Mismatch with a periodic checkpoint → INCOMPATIBLE
checkpointInterval / window / maxEvents30 s / 300 s / 20 000
productionSampleRate0.1
autoCaptureOnFailure / maxCapsulesPerSessiontrue / 3
captureNetworkBodies / maxBodyBytesoff in production; on in debug/QA / 256 KiBBool?: off in .production, on in .debug/.qa unless set; binary bodies need captureBinaryBodies: true (What's new)
redactKeys, redactHeaders, redactPatterns[]redactPatterns: [NSRegularExpression]
beforeRecordnil(type, data) throws -> JSONObject?; nil or throw drops the event
beforeCheckpointnil(integration, data) throws -> JSONValue?
outboxLimits10 / 10 MiB / 7 daysOutboxLimits(maxCount:maxBytes:maxAge:)
maxStaleConfig7 days
ignoreErrornil(Error) -> Bool
labels[:]Merged with the capture note
replayURLnilTests only; honoured in DEBUG builds

Replay with the CLI

{
  "runtime": "ios",
  "ios": {
    "project": "Shop.xcodeproj",
    "scheme": "Shop",
    "configuration": "Debug",
    "bundleId": "com.example.shop",
    "replayTest": "ShopUITests/BugCapsuleReplayTests/testReplay",
    "simulator": "iPhone 18 Pro",
    "startupSeconds": 120
  },
  "timeouts": { "buildSeconds": 1200, "attemptSeconds": 180 }
}
bugcapsule run <id>
  └─ xcodebuild build-for-testing   (once; BUGCAPSULE_GIT_SHA / BUGCAPSULE_GIT_DIRTY build settings)
  └─ per attempt:
       simctl uninstall <bundleId>   (fresh data container)
       TEST_RUNNER_BUGCAPSULE_REPLAY_URL=http://127.0.0.1:<port>/a/<token> \
       xcodebuild test-without-building -only-testing:<UITestTarget>/BugCapsuleReplayTests/testReplay
         └─ BugCapsuleReplayTestCase launches the app with BUGCAPSULE_REPLAY_URL + -BugCapsuleReplay
              └─ BugCapsule.start(): GET settings + capsule → restore UserDefaults/state
                 → at the first visible window: dispatch actions/text/lifecycle at recorded times,
                   serve URLSession fixtures, watch for the failure
                 → POST /result (+ BUGCAPSULE_RESULT:: line + accessibility element)

Storage and uploads

Demo app

Examples/Demo: UIKit home, SwiftUI cart, an in-process FakeShopServer (a URLProtocol below the SDK's). Generated from project.yml with XcodeGen; the generated project is checked in.

BugCapture path
Coupon SAVE100 makes small carts negativecheck("cart_total_non_negative"); fix toggle FIX_NEGATIVE_TOTAL
Recommendations before profile (~1 in 4) raise an NSExceptionUncaught NSException, written synchronously, uploaded next launch; profile request recorded pending
Legacy v0.9 cart_cache fails to decode in a later sessionreport(error:); reproduces only because the checkpoint restores UserDefaults
# Capture by hand (the SDK token on the command line, never committed)
cd Examples/Demo
xcodebuild test -project BugCapsuleDemo.xcodeproj -scheme BugCapsuleDemo \
  -destination 'id=<simulator udid>' -collect-test-diagnostics never \
  BUGCAPSULE_TOKEN=bcsdk.v1.… \
  -only-testing:BugCapsuleDemoUITests/CaptureFlowTests/testCaptureNegativeTotal

# Verify the isolated fix without touching tracked sources
BUGCAPSULE_IOS_BUILD_SETTINGS='DEMO_FIXES=FIX_NEGATIVE_TOTAL' bugcapsule verify <id> -p Examples/Demo

BUGCAPSULE_TOKEN (or, for a self-hosted setup, BUGCAPSULE_BACKEND_URL + BUGCAPSULE_INGEST_KEY, which win over the token) is read by the demo's own DemoConfig, not by the SDK. Your app passes the token to BugCapsule.start.

Limitations

Monitoring and release readiness

This SDK also sends error events, release-health sessions, traces and feedback. Configure those separately from capsule recording using Monitoring, upload release symbols, and complete the integration checklist. For approved artifacts, versions and upgrade rules, start with Installation and upgrades.