# iOS (Swift)

The `SplitHub` Swift package runs experiments and collects analytics in iOS and macOS apps. You create experiments in the dashboard; the app picks a variant on the device, with no network call on render, and sends what people saw and did. Read [Apps](/docs/apps) first for what differs from the web.

The iOS SDK is new. iOS 14+ and macOS 11+, no dependencies.

## Install

In Xcode: **File → Add Package Dependencies…**, paste the package URL and add `SplitHub` to your target. Or in `Package.swift`:

```swift
.package(url: "https://github.com/splithub-io/splithub-sdk", from: "0.5.0")
```

`npx splithub init` in an Xcode project prints these lines and a quick start. Native apps have no `splithub.config.ts`: experiments come from SplitHub Cloud.

## Start

Once, as early as you can. The public key (`pk_...`) and the property id (`sh-...`) are in the dashboard.

```swift
import SplitHub

SplitHub.start(publicKey: "pk_...", property: "sh-x1h78w")
```

## Variants and events

```swift
let button = SplitHub.variant("checkout-button")   // "control" or "green"
let price: Int? = SplitHub.value("price")          // payload of a value experiment

SplitHub.track("Purchase", props: ["revenue": 29]) // any event; a goal when marked as one
SplitHub.screen("Settings")                        // a page view of /Settings
SplitHub.identify(userId: "user-42", traits: ["plan": "pro"])
SplitHub.reset()                                   // on logout
```

The first variant of an experiment is the control.

## SwiftUI

```swift
import SwiftUI
import SplitHub

@main
struct ShopApp: App {
    init() {
        SplitHub.start(publicKey: "pk_...", property: "sh-x1h78w")
    }

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

struct CheckoutView: View {
    var body: some View {
        SplitHubExperiment("checkout-button") { variant in
            if variant == "green" {
                Button("Buy now") {}.foregroundColor(.green)
            } else {
                Button("Buy now") {}
            }
        }
        .splithubScreen("Checkout")
    }
}
```

`SplitHubExperiment` records the exposure when the view appears. `.splithubScreen` reports the screen each time it appears.

## Good to know

- **First launch.** The SDK waits up to 400 ms for the experiments (`Options(waitMs:)`) and shows the control meanwhile. Later launches decide at once from the copy on the device.
- **Offline.** Events wait on disk (up to 1,000) and go out when the network is back.
- **Sessions.** A new session starts after 30 minutes in the background.
- **QA.** Force a variant with `Options(force: ["checkout-button": "green"])`. Forced views are never counted.
- **Previews and tests.** SwiftUI previews send nothing. Pass `Options(disabled: true)` in tests.
- **Targeting.** Flows can use `platform` (`ios`, `macos`) and `app_version` (at least / below). See [Targeting flows](/docs/targeting).
