# Native Swift

## Install

Download [Submetry.swift](https://submetry.com/sdk/Submetry.swift) and add it to your application target. The file contains the complete SDK. It needs no external dependency and supports iOS 13+. Source-file installation does not require `import Submetry`. A local Swift Package is also available at `sdk/swift` in the Submetry repository; import the module when using that package.

## Configure at launch

Call once from your app's initialization or application delegate. If RevenueCat is present, initialize Purchases before Submetry:

```swift
import Foundation
// import RevenueCat, if already used by your app
// Purchases.configure(withAPIKey: yourExistingRevenueCatKey)
Submetry.configure(
    appId: "YOUR_APP_ID",
    key: "YOUR_PUBLIC_KEY",
    // userId: Purchases.shared.appUserID, // if RevenueCat is configured
    endpoint: URL(string: "https://api.submetry.com/v1/events")!
)
```

Do not configure in a SwiftUI view body or a repeated `onAppear`. `apiKey:` is an alias for `key:`. The key must start with `sub_pk_`. HTTPS is required outside localhost development.

## Identity

The SDK persists a generated anonymous installation ID. Configure with RevenueCat's current app user ID, including its anonymous ID, to join purchases with the installation. After a successful RevenueCat login or logout, call `Submetry.identify(Purchases.shared.appUserID)` using the resulting ID. If another authentication system is used, use its stable non-sensitive identifier.

`identify` records `identity_linked` and changes the user ID on future events. Existing anonymous events link through the observed identity graph. The current SDK has no public reset/consent API. Shared-device account isolation needs explicit product review; do not assume identify resets an installation.

## Instrument

```swift
Submetry.onboardingStep(0, id: "goal", answer: "strength")
Submetry.onboardingCompleted()
Submetry.track("activation_completed")
Submetry.paywallShown("settings")
Submetry.paywallPlanSelected("monthly")
Submetry.purchaseCompleted("monthly") // confirmed paid purchase only
Submetry.paywallDismissed()
Submetry.track("export_completed", properties: ["format": "pdf"])
```

`trialStarted` is the outcome for a confirmed free trial. Do not send both trial and paid purchase outcomes for the same initial transaction. `paywallShown` sets paywall context on subsequent events until `paywallDismissed` clears it. Use stable placements and product identifiers.

## Automatic events and context

`first_open` is recorded once per persisted SDK installation state. `session_start` and `app_open` occur at configure and each foreground entry. Do not emit them manually. The SDK attaches App ID, event ID, timestamp, anonymous ID, session ID, optional user ID, platform, version, build, OS, hardware device model, locale, timezone and environment.

On iOS 14.3+, the SDK automatically requests an AdServices token off the main thread once per installation and submits an `install_attribution` event. The server resolves and removes the token before raw persistence. Set `appleAdsAttribution: false` in `configure` to disable collection. [Apple Ads](https://submetry.com/docs/apple-ads.md) explains campaign reporting and identity matching.

Debug builds default to `debug`. A sandbox receipt defaults to `sandbox`; it cannot reliably distinguish TestFlight. Pass `environment: "testflight"` explicitly for known TestFlight builds. Other release builds default to `production`.

## Delivery and diagnostics

Events persist under Application Support before upload. The SDK sends batches of up to 20, on a ten-second timer, at 20 buffered events, on background entry, or with `Submetry.flush()`. Failed requests retain event IDs and retry with exponential backoff capped at five minutes.

Invalid 400/413/422 batches are archived to `queue.json.rejected.json` for inspection. Authentication errors retain events for retry. A corrupted queue is archived before creating new state; failed archival pauses telemetry to preserve the original data.

```swift
Submetry.onError = { message in
    // Send to your development logger; never expose keys or sensitive properties.
    print("Submetry: \(message)")
}
Submetry.flush()
```

See [Quickstart](https://submetry.com/docs/quickstart.md), [Events](https://submetry.com/docs/events.md) and [RevenueCat](https://submetry.com/docs/revenuecat.md).
