# Host App SDK & Headless API

`iOSparkle` is a single SwiftPM library target: no resources, no third-party dependencies, iOS 16 and later. One object, `IOSparkleUpdater`, fetches the Feed, decides whether a build is installable, presents updates, and hands installation to iOS. Import it behind your explicit compilation condition (see [Quickstart](quickstart.md)).

```swift
#if IOSPARKLE_ENABLED
import iOSparkle
#endif
```

All names in this chapter are public API unless stated otherwise.

```swift
@MainActor
public final class IOSparkleUpdater: ObservableObject
```

## Create an updater

```swift
@MainActor
enum Updates {
    static let updater = IOSparkleUpdater(
        channelURL: URL(string: "https://ota.example.com/my-app-dev")!,
        configuration: .init(feedHeaders: ["Authorization": "Bearer <token>"])  // optional
    )
}
```

`channelURL` is the Channel directory. A trailing slash is added if missing, and the normalized value is exposed as `updater.channelURL`. The Feed is always read from `<channelURL>feed.json`.

`IOSparkleUpdater` is `@MainActor` and an `ObservableObject`, so it is created and used from the main actor. Store it with `@StateObject` or `@ObservedObject` in SwiftUI, or subscribe to `updater.$state` with Combine in UIKit.

## Observable state

```swift
@Published public private(set) var state: IOSparkleUpdater.State
public let channelURL: URL
public var localVersion: String?   // CFBundleShortVersionString of the running app
public var localBuild: Int?        // CFBundleVersion of the running app, as an integer
public var dismissedBuild: Int?    // the build the user chose Later for, if any
```

### `State`

```swift
public enum State: Sendable, Equatable {
    case idle
    case checking
    case updateAvailable(Release, Installability)
    case upToDate(Release?, Installability)
    case unavailable
}
```

| Case | Meaning |
| --- | --- |
| `idle` | No check has finished yet. |
| `checking` | A Feed request is in flight. |
| `updateAvailable(release, installability)` | `release.build` is greater than the local build. |
| `upToDate(release, installability)` | The Feed's build is not newer. The release is kept so it can be reinstalled. |
| `unavailable` | A manual check failed: no HTTP `200`, a network error, or a Feed that is malformed, written for another bundle, or for a newer schema. |

Two rules are worth knowing when you drive your own UI:

- A failed **automatic** check restores the previous state instead of showing `.unavailable`, so a flaky connection never erases an update that was already found.
- A Feed with `schemaVersion` greater than `1` is ignored the same way: it is not malformed, it is merely newer than this updater understands.

### `Release`

A one-to-one image of the Channel's `feed.json`:

```swift
public struct Release: Sendable, Equatable {
    public let bundleId: String
    public let version: String
    public let build: Int
    public let manifestURL: URL
    public let publishedAt: Date?
    public let commit: String?
    public let minimumOSVersion: String?
    public let releaseNotes: String?
    public let sizeBytes: Int64?
    public let sha256: String?
}
```

`manifestURL` is always an absolute `https` URL: the Feed's `manifestURL` if it has one, otherwise `manifest.plist` inside the Channel directory.

### `Installability`

```swift
public enum Installability: Sendable, Equatable {
    case installable
    case simulatorUnsupported
    case incompatibleOS(minimumVersion: String)
}
```

`installability(for: release)` reports it for any release, now or later. The Simulator check comes first; then the device's OS version is compared with `release.minimumOSVersion`, component by component, with missing components counting as zero (`17` and `17.0` are equal). A `minimumOSVersion` that is not dot-separated digits, such as `17..0`, makes the release uninstallable.

## `Configuration`

```swift
public struct Configuration: Sendable {
    public var throttleInterval: Duration
    public var requestTimeout: TimeInterval
    public var feedHeaders: (@Sendable () async -> [String: String])?
    public var presentsAutomaticAlert: Bool
    public var allowsAutomaticChecksInDebugBuilds: Bool
    public var isBusy: (@MainActor () -> Bool)?
    public var customUpdatePresenter: (@MainActor (Release, IOSparkleUpdater) -> Void)?
    public var beforeExitForInstall: (@MainActor () async -> Void)?
    public var exitHookTimeout: Duration
}
```

| Property | Default | Purpose |
| --- | --- | --- |
| `throttleInterval` | `.seconds(30)` | Minimum time between two automatic checks, measured with `ContinuousClock` so the interval keeps counting while the device sleeps. Manual checks are never throttled. |
| `requestTimeout` | `4` | Timeout in seconds for the Feed request. A timeout or offline device ends the check silently. |
| `feedHeaders` | `nil` | Headers added to every `feed.json` request. The closure is called afresh for each request, so it can refresh a token. |
| `presentsAutomaticAlert` | `true` | `false` turns off the built-in automatic alert — the `UIAlertController` — and nothing else. The updater then only updates `state`. The Developer Updates components (`IOSparkleDebugSection`, `IOSparkleDebugView`, `IOSparkleDebugViewController`) are yours to embed and keep working. |
| `allowsAutomaticChecksInDebugBuilds` | `false` | Set `true` to get automatic checks in a `DEBUG` build run from Xcode. |
| `isBusy` | `nil` | Return `true` while the app is in a flow an alert must not interrupt. It is the last of the four presentation gates, evaluated when an automatic check finds a newer installable build. It never changes `state`. |
| `customUpdatePresenter` | `nil` | Replaces the built-in alert. Called with the release and the updater, after the same four presentation gates. Takes priority over `presentsAutomaticAlert`. |
| `beforeExitForInstall` | `nil` | Runs after iOS accepts the install request and before the process exits. Flush state here. |
| `exitHookTimeout` | `.seconds(2)` | How long `beforeExitForInstall` may take. See [Installing](#installing). |

`feedHeaders` is for the Feed request only. That request is made by the Host App, which is the only party in the flow able to send a header; iOS fetches the manifest and the package on its own, with nothing attached. [Self-Hosting & Private Channels](self-hosting.md) shows how to combine headers with short-lived manifest links.

`Configuration` has a second initializer whose `feedHeaders` parameter is a plain `[String: String]`, which is what the example above uses.

## Lifecycle

```swift
public func startAutomaticChecks()
public func stopAutomaticChecks()

@discardableResult
public func refreshNow() async -> Release?
```

`startAutomaticChecks()` begins observing scene lifecycle events:

- A check starts whenever a scene activates, including immediately if a window scene is already active when you call it.
- A check in flight is cancelled when the scene deactivates or enters the background, and its previous state is restored.
- At most one check runs at a time, and automatic checks respect `throttleInterval`.
- Calling it twice is harmless. `stopAutomaticChecks()` removes the observation and cancels an automatic check in flight. Releasing the updater does the same.

In SwiftUI, `.iOSparkleUpdater(updater)` is `onAppear { updater.startAutomaticChecks() }`. No scene-delegate forwarding is needed in either toolkit.

`refreshNow()` checks the Feed immediately, whatever the throttle state, and never presents UI. It returns the `Release` it found, or `nil` when the check failed or was cancelled. Starting a new check replaces one that is already in flight.

## What a check does

1. **Request.** `GET <channelURL>feed.json` with `reloadIgnoringLocalAndRemoteCacheData`, `requestTimeout`, and the `feedHeaders`. It uses an ephemeral `URLSession` without cache, cookie storage, or credential storage, and follows a redirect only if the target is `https`.
2. **Validate.** The response must be HTTP `200`, the Feed must decode as schema version `1`, `bundleId` must equal `Bundle.main.bundleIdentifier`, and the manifest URL must be `https`. The Channel URL itself must be `https` as well; nothing is requested otherwise.
3. **Decide.** `state` becomes `.updateAvailable` or `.upToDate`, carrying the release and its `Installability`.
4. **Present** (automatic checks only, and only for a newer, installable build): pass the gates, then call `customUpdatePresenter` if set, or show the built-in alert if `presentsAutomaticAlert`.

The presentation gates run in this order, exactly as in the updater's `presentAutomaticUpdate(_:)`: the app is not installing (`!isInstalling`); the process is not a test host (`!isRunningTests()`); the build is not the one dismissed with **Later** (`dismissedBuild != release.build`); and `isBusy?() != true`. Only then is `customUpdatePresenter` called if it is set, or the built-in alert shown if `presentsAutomaticAlert` is `true`.

The gates exist for automatic presentation only. `refreshNow()` and the Developer Updates components never consult them, and no gate changes `state`. One consequence matters for a headless UI: with `presentsAutomaticAlert` set to `false` and no `customUpdatePresenter`, the gates are still evaluated but nothing is presented either way, so `isBusy` has no observable effect — `state` becomes `.updateAvailable` regardless. A headless UI applies its own busy flag (see [Headless mode](#headless-mode)) or uses `customUpdatePresenter` to have the gates applied for it.

## Runtime matrix

The updater changes its behavior on its own in five situations. All of them leave the manual path — `refreshNow()` and the Developer Updates components — working.

| Where the Host App is running | Automatic checks and alerts | `installability(for:)` |
| --- | --- | --- |
| Physical device, installed from the Channel (`-O` build) | On: every scene activation, throttled 30 seconds | `.installable`, or `.incompatibleOS` below `minimumOSVersion` |
| Physical device, run from Xcode (`Debug`, `DEBUG` defined) | Off by default; on with `allowsAutomaticChecksInDebugBuilds: true` | `.installable` |
| iOS Simulator | Off | `.simulatorUnsupported` |
| Device on an OS older than `minimumOSVersion` | The Feed is still checked so `state` is current, but no alert is shown | `.incompatibleOS(minimumVersion:)` |
| XCTest or UI Test host (launched by `XCUIApplication`) | Off, and nothing is ever presented automatically | Computed normally |

`DEBUG` is a property of the compiled library, not of your app's own `#if DEBUG` code: it is set only when the `iOSparkle` module is compiled in Xcode's `Debug` configuration (`-Onone`). A configuration cloned from `Release`, such as `DevOTA`, compiles the library with `-O` and without `DEBUG`, so an OTA build installed from the Channel behaves like the first row.

A test host is recognized through the process's `XCTestConfigurationFilePath`, `XCTestSessionIdentifier`, or `XCTestBundlePath`, an `XCT` library in `DYLD_INSERT_LIBRARIES`, or the presence of the `XCTestCase`, `XCTAutomationSession`, or `XCTTargetBootstrap` classes. [Troubleshooting](troubleshooting.md) lists the complete set of reasons the updater may stay silent.

## Built-in UI

### The automatic alert

The built-in presenter shows a `UIAlertController` with the title **Update Available**.

- The message starts with one structured line, `1.4.0 (118) · 79806e2`: version, build, and the first seven characters of the commit, followed by the download size when the Feed provides it (formatted with `ByteCountFormatter`, so its exact text follows the device). Parts that the Feed does not provide are left out. If the Feed has `releaseNotes`, up to six lines and 280 characters of plain text follow.
- **Later** (`UIAlertAction.Style.cancel`) calls `dismissUpdate(build:)` for that build. **Update** (the preferred action) calls `installUpdate()`.
- Before showing anything, the updater locates the key window among the app's `.foregroundActive` window scenes and walks the entire view-controller tree below its root. If any controller is presenting or dismissing a controller, is itself being presented or dismissed, or is mid-transition, the alert is skipped for this check. `state` is still `.updateAvailable`, and the next automatic check after the throttle interval tries again.

The window is looked at only after the `isBusy` and dismissal gates have passed, so a busy or dismissed app never touches the view hierarchy.

### Developer Updates components

Three components cover the developer-facing side: two SwiftUI views, and a UIKit view controller that hosts one of them. They work in every runtime in the matrix above and never start automatic checks.

| Component | What it shows |
| --- | --- |
| `IOSparkleDebugSection(updater:)` | A `Section` for a `Form` or `List`: a status row, the primary action, and a **Developer Updates** link to the detail screen. Header: **Channel Feed**. |
| `IOSparkleDebugView(updater:)` | The detail screen: the same status and action, **Installed Build** (version, build, bundle ID), **Channel Feed** (version, build, published date, minimum iOS, download size, commit with copy buttons), **Open Channel Page**, the dismissed build, and **Reset Dismissed Update**. |
| `IOSparkleDebugViewController(updater:)` | A UIKit view controller hosting `IOSparkleDebugView`. Push it on a `UINavigationController`. |

The primary action adapts to the state: **Check Now** when nothing is loaded or unavailable, **Update** when a newer installable build exists, **Reinstall** when the current build matches the Feed, a disabled row with the reason on a Simulator or an incompatible OS, and a progress indicator while checking. The components refresh the Feed when they appear, bypassing the automatic throttle.

**Open Channel Page** calls `openChannelPage()`, which opens the Channel URL in Safari.

### Previews

`IOSparkleUpdater.preview(state:)` builds an updater whose state is seeded and frozen. It never touches the network, never starts checks, and ignores dismissal persistence, which makes it safe in SwiftUI previews and unit tests.

```swift
let sample = IOSparkleUpdater.Release(
    bundleId: "com.example.myapp.dev", version: "1.4.0", build: 118,
    manifestURL: URL(string: "https://ota.example.com/my-app-dev/manifest.plist")!,
    commit: "79806e2e", releaseNotes: "Plain-text summary", sizeBytes: 25_629_710
)

#Preview("Update available") {
    IOSparkleDebugSection(updater: .preview(state: .updateAvailable(sample, .installable)))
}
```

Its full signature:

```swift
public static func preview(
    state: State,
    channelURL: URL = URL(string: "https://ota.example.com/app-dev/")!,
    localVersion: String = "1.0.0",
    localBuild: Int = 100,
    dismissedBuild: Int? = nil
) -> IOSparkleUpdater
```

### Localization

Every built-in string exists in English, Simplified Chinese, and Traditional Chinese, compiled into the library as plain Swift code. The language is the first match in `Bundle.main.preferredLocalizations`, then in `Locale.preferredLanguages`, and falls back to English. A bare `zh` resolves to Simplified Chinese; `zh-TW`, `zh-HK`, and `zh-MO` resolve to Traditional Chinese.

## Headless mode

To draw your own UI, set `presentsAutomaticAlert` to `false` (or supply `customUpdatePresenter`). The updater then stops showing its own alert and only maintains `state` — the Developer Updates components, if you embed them, keep working — and you present, dismiss, and install with the atomic methods:

| Method | Effect |
| --- | --- |
| `refreshNow() async -> Release?` | Checks the Feed now. Never presents anything. |
| `installability(for: Release) -> Installability` | Whether and why a release can be installed here. |
| `dismissUpdate(build: Int)` | Suppresses automatic presentation for that one build. Persisted in `UserDefaults.standard`, separately per Channel and bundle identifier. |
| `resetDismissedUpdate()` | Clears that suppression. |
| `installUpdate() async -> Bool` | Starts the install flow described below. |
| `openChannelPage() async -> Bool` | Opens the Channel URL in Safari. |

A complete headless setup with a custom prompt:

```swift
#if IOSPARKLE_ENABLED
import SwiftUI
import iOSparkle

@MainActor
final class AppFlow: ObservableObject {
    @Published var busy = false  // your flows set this; the prompt below is never offered while it is true
}

@MainActor
enum Updates {
    static let updater = IOSparkleUpdater(
        channelURL: URL(string: "https://ota.example.com/my-app-dev")!,
        configuration: .init(presentsAutomaticAlert: false)  // no built-in alert; `state` is all we observe
    )
}

struct UpdatePrompt: View {
    let release: IOSparkleUpdater.Release
    let onLater: () -> Void
    let onUpdate: () -> Void

    var body: some View {
        VStack(spacing: 12) {
            Text("Version \(release.version) (\(release.build)) is available")
            if let notes = release.releaseNotes { Text(notes) }
            HStack {
                Button("Later", action: onLater)
                Button("Update", action: onUpdate).buttonStyle(.borderedProminent)
            }
        }
        .padding()
    }
}

struct RootView: View {
    @ObservedObject private var updater = Updates.updater
    @StateObject private var flow = AppFlow()  // however your app owns its flow state
    @State private var offeredBuild: Int?

    var body: some View {
        ContentView()
            .iOSparkleUpdater(updater)
            .onChange(of: updater.state) { _ in offerIfNeeded() }
            .onChange(of: flow.busy) { _ in offerIfNeeded() }
            .sheet(isPresented: Binding(get: { offeredRelease != nil }, set: { if !$0 { offeredBuild = nil } })) {
                if let release = offeredRelease {
                    UpdatePrompt(
                        release: release,
                        onLater: {
                            updater.dismissUpdate(build: release.build)
                            offeredBuild = nil
                        },
                        onUpdate: { Task { await updater.installUpdate() } }
                    )
                }
            }
    }

    // The prompt's own gates: a newer installable build, the app not busy, and this build neither
    // offered already nor dismissed with Later. `isBusy` is not consulted here: with the built-in
    // alert off and no custom presenter, `isBusy` gates nothing.
    private func offerIfNeeded() {
        guard case let .updateAvailable(release, .installable) = updater.state, !flow.busy,
              release.build != offeredBuild, release.build != updater.dismissedBuild else { return }
        offeredBuild = release.build
    }

    private var offeredRelease: IOSparkleUpdater.Release? {
        guard case let .updateAvailable(release, .installable) = updater.state, release.build == offeredBuild
        else { return nil }
        return release
    }
}
#endif
```

`customUpdatePresenter` is the alternative for UIKit, or for a prompt that does not need to be part of the view hierarchy. It is called by an automatic check that found a newer installable build, and only after the same four gates as the built-in alert — not installing, not a test host, the build not dismissed with **Later**, and `isBusy` not `true` — so those gates are applied for you. It is never called by `refreshNow()`.

```swift
@MainActor
enum PromptQueue {
    static var pendingUpdate: IOSparkleUpdater.Release?   // your UI observes this and shows its prompt
}

@MainActor
enum Updates {
    static let updater = IOSparkleUpdater(
        channelURL: URL(string: "https://ota.example.com/my-app-dev")!,
        configuration: .init(customUpdatePresenter: { release, _ in
            PromptQueue.pendingUpdate = release   // keep the second argument if your prompt calls installUpdate() or dismissUpdate(build:)
        })
    )
}
```

## Installing

`installUpdate()` returns `false` without side effects when there is no current installable release (the state must be `.updateAvailable(_, .installable)` or `.upToDate(_, .installable)`), when an install is already in progress, or when the system declines to open the install URL. That last case is what happens when the user taps **Cancel** in the system dialog, or on a Simulator. Nothing has been changed; the call can be retried.

When the system accepts the request, `installUpdate()`:

1. Cancels any check in flight.
2. Asks each open scene for its `stateRestorationActivity` and stores it, so the app returns to the same screen after relaunch.
3. Runs `beforeExitForInstall`, bounded by `exitHookTimeout`.
4. Calls `exit(0)` and returns `true`.

The exit is mandatory, and so is the timeout. After the user confirms, iOS replaces the app in place but waits for it to leave the foreground. A hook that hangs — an async flush waiting on a socket, say — keeps the process alive and deadlocks the system's installation coordinator, `runningboardd`, which is waiting for the app to terminate. The updater therefore waits at most `exitHookTimeout` (2 seconds by default), cancels the hook's task at the deadline, and exits regardless. Keep the hook short and make it honor cancellation.

From there iOS owns the process: it shows progress on the Home Screen icon, then relaunches the updated app. A failure after the handoff — an unreachable manifest, a device missing from the profile, an untrusted certificate — is reported through a system alert, never to the app. That is why `iosparkle verify` belongs in the publishing pipeline: see [CLI & App Store Audit](cli-and-audit.md).

### Writing the exit hook

Two ways of writing the hook compile reliably. A hook that awaits only main-actor functions can be passed inline. A hook that awaits anything else — a nonisolated async function, an actor method, even `Task.yield()` — must have its configuration declared in a separate statement:

```swift
@MainActor
enum Updates {
    private static let configuration = IOSparkleUpdater.Configuration(
        beforeExitForInstall: { await Log.flush() }        // awaits off the main actor
    )
    static let updater = IOSparkleUpdater(
        channelURL: URL(string: "https://ota.example.com/my-app-dev")!,
        configuration: configuration
    )
}
```

Written inline inside the `IOSparkleUpdater(…)` call, that same closure is rejected by the Swift 6 compiler with `default argument cannot be both main actor-isolated and @concurrent`, a diagnostic about the initializer's default arguments rather than about the closure. The separate declaration avoids it.
