Examples

Finished examples of the Apple SDK in an app — minimal setup, your own exporter, tuning capture services, screens and spans, SwiftUI, and crash context.

Every example below works as written. What each setting means is covered in Configuration; this page shows only the finished shape.

Minimal setup

AppDelegate.swift
import UIKit
import SophonzIO
 
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
  func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    do {
      try Sophonz.start(options: Sophonz.Options.fromPlist() ?? .withCollector(
        url: "https://in.sophonz.ai",
        appKey: "sk_…"
      ))
    } catch {
      // No instrumentation is better than no launch.
      print("[sophonz] failed to start: \(error)")
    }
    return true
  }
}

That alone captures network requests, screen transitions, taps, WebView loads, memory warnings, low power mode, and crashes.

Sending through your own exporter

This is how to receive data before the Sophonz collector transport is wired. Start without an appId and supply exporters.

AppDelegate.swift
import SophonzIO
import OpenTelemetrySdk
import OpenTelemetryProtocolExporterHttp
 
func startSophonz() {
  let endpoint = URL(string: "https://in.sophonz.ai/v1/traces")!
  let spanExporter = OtlpHttpTraceExporter(endpoint: endpoint)
 
  let otel = Sophonz.OTelOptions(
    resource: Resource(attributes: [
      "deployment.environment.name": .string("production")
    ]),
    spanExporters: [spanExporter]
  )
 
  do {
    try Sophonz.start(options: .withLocalConfiguration(otel: otel))
  } catch {
    print("[sophonz] failed to start: \(error)")
  }
}

service.name, service.version, and telemetry.sdk.language are always set by the SDK, so putting them in resource does not override them.

Tuning capture services

Turning on hang detection, excluding one internal screen from screen capture, and ignoring health-check requests.

import SophonzIO
 
let services = Sophonz.CaptureServicesOptionsBuilder()
  .addDefaults()
  .addHangCaptureService()
  .addUrlSessionCaptureService(
    withOptions: URLSessionCaptureService.Options(
      ignoredURLs: ["/health", "/ready"],
      traceparent: .init(onlyAllowDomains: ["api.example.com"])
    )
  )
  .addViewCaptureService(
    withOptions: ViewCaptureService.Options(
      viewControllerBlockList: ViewControllerBlockList(names: ["DebugMenu"])
    )
  )
  .build()
 
try Sophonz.start(options: .withCollector(
  url: "https://in.sophonz.ai",
  appKey: "sk_…",
  captureServices: services
))

Calling addDefaults() first matters. The builder starts empty, so leaving it out installs only the three services added here.

onlyAllowDomains narrows where traceparent is attached, which keeps internal trace IDs from reaching third-party APIs outside your control.

User and session properties

Attaching identity and classification at sign-in.

func onSignIn(user: User) {
  Sophonz.shared.userIdentifier = user.internalId
  Sophonz.shared.addPersona("subscriber", lifespan: .permanent)
  Sophonz.shared.setProperty(
    key: "plan",
    value: user.plan,
    lifespan: .session
  )
}
 
func onSignOut() {
  Sophonz.shared.userIdentifier = nil
  Sophonz.shared.removeAllPersonas(lifespans: [.permanent, .session])
  Sophonz.shared.endUserSession()
}

Spans of your own

Recording an interval no capture service sees.

func checkout(cart: Cart) async throws -> Order {
  let span = Sophonz.shared.createSpan(
    name: "checkout",
    type: .performance,
    attributes: ["cart.items": String(cart.items.count)]
  )
 
  do {
    let order = try await api.submit(cart)
    span?.end()
    return order
  } catch {
    Sophonz.shared.log(
      "Checkout failed",
      severity: .error,
      attributes: ["cart.items": String(cart.items.count)]
    )
    span?.end(errorCode: .failure)
    throw error
  }
}

Enriching the startup trace

Extending the startup trace to the point the app is genuinely usable.

func warmUpCaches() async {
  let start = Date()
  await cache.preload()
 
  Sophonz.shared.createStartupChildSpan(
    name: "cache-preload",
    startTime: start,
    endTime: Date()
  )
  Sophonz.shared.addAttributesToStartupTrace(["cache.warm": "true"])
}

SwiftUI screens

Screen capture excludes UIHostingController by default, so SwiftUI screens are marked with the view modifier.

import SwiftUI
import SophonzIO
 
struct OrderListView: View {
  @State private var orders: [Order] = []
 
  var body: some View {
    List(orders) { OrderRow(order: $0) }
      .task { orders = await loadOrders() }
      // Treats the time until orders is populated as the loading interval.
      .sophonzTrace("OrderListView", contentComplete: orders.count)
  }
}

Leaving context for a crash

Nothing runs after a crash, so the context has to be in place beforehand — updated as state changes.

func didOpenScreen(_ name: String) {
  Sophonz.shared.appendCrashInfo(key: "last.screen", value: name)
  Sophonz.shared.addBreadcrumb("Opened screen: \(name)")
}

At launch you can check how the previous run ended.

if Sophonz.shared.lastRunEndState() == .crash {
  // Show a recovery screen, or restore unsaved work.
}

Recording push notifications yourself

For when automatic capture is off, or you want to control where it happens.

extension AppDelegate: UNUserNotificationCenterDelegate {
  func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
  ) {
    Sophonz.shared.addPushNotificationEvent(
      notification: response.notification,
      captureData: false
    )
    completionHandler()
  }
}

Passing captureData: false leaves out the title and body. Use it where notification content may contain personal data.

Verifying

Run the app in the simulator, move between a few screens, then send it to the background — nothing is uploaded while it stays in the foreground. Check that Sophonz.shared.state is .started and isSDKEnabled is true first.

If the app's page in the portal is empty while the collector is accepting the data, check AppName against the name the app is registered under: the portal matches on (project, service.name).

If you started in the legacy appId mode, the default endpoints are on the .invalid domain and reach nothing. Start with an app key instead — see Configuration.