# iOS API Reference

## WarpLink

The main entry point. All methods are static.

```swift
public final class WarpLink
```

### Properties

| Property | Type | Description |
|----------|------|-------------|
| `sdkVersion` | `String` | The current SDK version (`"1.4.1"`). |
| `isConfigured` | `Bool` | Whether `configure()` has been called. Thread-safe. |
| `isApiKeyValid` | `Bool?` | The server's key validation verdict: `true`, `false` (rejected or revoked), or `nil` if not yet determined. |
| `attributionResult` | `WarpLinkDeepLink?` | The cached result of the last deferred deep link check. |
| `isAttributionComplete` | `Bool` | Whether the deferred attribution check has finished for this install. |
| `deferredCheckStatus` | `DeferredCheckStatus` | Where the deferred check stands, read without sending a request. It tells a skipped check from no match. See [DeferredCheckStatus](#deferredcheckstatus). |
| `lastTetherTestReceipt` | `String?` | The receipt of the last Tether test code the server took. The SDK forgets it when the app starts, and `clearAttribution()` clears it. |

### configure(apiKey:options:)

```swift
public static func configure(
    apiKey: String,
    options: WarpLinkOptions? = nil
)
```

Initialize the SDK. Must be called before any other SDK methods.

| Parameter | Type | Description |
|-----------|------|-------------|
| `apiKey` | `String` | Your WarpLink SDK key (`wl_live_` for release builds or `wl_test_` for debug builds, then 32 alphanumeric chars). Create it in the dashboard under **Keys** > **SDK keys**. An API key is rejected by install attribution. |
| `options` | `WarpLinkOptions?` | Optional configuration overrides, including the `onLink` callback and opt-out flags. |

Validates the key format locally, then performs async server-side validation via `/sdk/validate`. The validation result is cached for 24 hours.

Call it once at startup. A second call with the same key and equal options keeps the running session and its deferred check, and only takes the new `onLink`. A different key or different options start a new session, and abandon a check still in flight.

When `options.onLink` is set, `configure()` also wires up cold start, warm start, and the deferred deep link check. The single callback receives every resolved link (a tap or a deferred install match). Set `autoDeepLinkHandling` or `autoDeferredCheck` to `false` to disable either piece and drive it with the manual methods below.

### continue(\_:) and open(\_:)

```swift
@discardableResult
public static func `continue`(_ userActivity: NSUserActivity) -> Bool

@discardableResult
public static func open(_ url: URL) -> Bool
```

Forward an incoming Universal Link to the SDK from your scene or app delegate. The SDK resolves it and dispatches to `onLink`. Use these when you keep your own delegate instead of the drop-in `WarpLinkSceneDelegate` / `WarpLinkAppDelegate`. `continue(_:)` extracts `webpageURL` and forwards it to `open(_:)`.

Both return `true` if the URL was a WarpLink link the SDK will handle: a WarpLink domain **and** a path of exactly one segment, which is what a slug always is. A custom domain counts as a WarpLink domain once you declare it in `linkDomains` or `WarpLinkDomains`. They return `false` (and do nothing) when `configure()` has not run, when `autoDeepLinkHandling` is disabled, when the URL is not on a WarpLink domain, or when the path is not a single segment. By default your app is associated with every path on the domain, so pass every URL here and route the ones that return `false` with your own router.

### isWarpLinkURL(\_:)

```swift
public static func isWarpLinkURL(_ url: URL) -> Bool
```

Check whether a URL is a WarpLink link, without resolving it. Useful when a host has its own router and needs to decide whether to hand a URL to WarpLink at all, since `open(_:)` and `continue(_:)` resolve as a side effect (claiming the tap, deduping, calling the API). Uses the same WarpLink domain and single-path-segment rule as `open(_:)`/`continue(_:)`.

| Parameter | Type | Description |
|-----------|------|-------------|
| `url` | `URL` | The URL to check. |

### handleDeepLink(\_:completion:)

```swift
public static func handleDeepLink(
    _ url: URL,
    completion: @escaping (Result<WarpLinkDeepLink, WarpLinkError>) -> Void
)
```

Resolve an incoming Universal Link URL to a deep link.

| Parameter | Type | Description |
|-----------|------|-------------|
| `url` | `URL` | The Universal Link URL received by the app. |
| `completion` | `(Result<WarpLinkDeepLink, WarpLinkError>) -> Void` | Called on the **main thread**. |

**Errors:** `.notConfigured`, `.invalidURL`, `.linkNotFound`, `.passwordRequired`, `.networkError`, `.serverError`, `.invalidApiKey`, `.decodingError`

### checkDeferredDeepLink(completion:)

```swift
public static func checkDeferredDeepLink(
    completion: @escaping (Result<WarpLinkDeepLink?, WarpLinkError>) -> Void
)
```

Check for a deferred deep link on first launch. Returns `nil` if no match found. Called automatically by `configure()` unless `autoDeferredCheck` is `false`.

| Parameter | Type | Description |
|-----------|------|-------------|
| `completion` | `(Result<WarpLinkDeepLink?, WarpLinkError>) -> Void` | Called on the **main thread**. |

On first launch, collects device signals (preferred language, timezone offset, IDFV) and sends them to the attribution API. The server derives the IP and computes the match key. On subsequent launches, returns the cached result.

"First launch" means the first launch of the current install. A reinstall is a new install and runs the check again, with `is_reinstall` set on the request. See [App Reinstall](https://warplink.app/docs/sdks/ios/deferred#app-reinstall).

**Errors:** `.notConfigured`, `.networkError`, `.serverError`, `.invalidApiKey`, `.keyAppMismatch`, `.decodingError`

### redeemInvitation(text:completion:)

```swift
public static func redeemInvitation(
    text: String,
    completion: @escaping (Result<WarpLinkDeepLink?, WarpLinkError>) -> Void
)
```

Redeem a referral invitation the person pasted. Call it from a user action with the text the system paste control hands you. This call reads nothing from the pasteboard. The paste button reads it only on a tap, automatic mode reads once on first open, and on call mode reads when your app calls `readTether`.

| Parameter | Type | Description |
|-----------|------|-------------|
| `text` | `String` | The pasted text. |
| `completion` | `(Result<WarpLinkDeepLink?, WarpLinkError>) -> Void` | Called on the **main thread**. `.success(link)` is a match, also cached as `attributionResult`. `.success(nil)` means the text was not an invitation or matched nothing. |

An invitation that is invalid or expired fails with `.serverError` and a message that says how to open the link again. After a network failure the SDK keeps the invitation and tries again on a later launch, a bounded number of times. Skipping this call, or any failure, leaves the app fully usable.

`WarpLinkPasteButton` (SwiftUI, iOS 16) and `WarpLinkUIPasteButton` (UIKit, iOS 16) wrap the system paste control and call this method with the text it returns. Both take an `onResult` closure with the same `Result`. See [Referral Invitations](https://warplink.app/docs/sdks/ios/attribution#referral-invitations).

**Errors:** `.notConfigured`, `.serverError`, `.networkError`

### claimReferral(installerId:completion:)

```swift
public static func claimReferral(
    installerId: String,
    completion: @escaping (Result<ReferralClaimResult, WarpLinkError>) -> Void
)
```

Credit the referral behind this install to the person who just signed up. `installerId` is your own stable id for them, 1 to 128 characters. The call is safe to repeat: the same id gets the same answer and is never credited twice. A status of `.none` is an ordinary answer, not an error.

`ReferralClaimResult` carries these properties:

| Property | Type | Description |
|----------|------|-------------|
| `status` | `Status` | `.claimed`, `.flagged`, `.ignored` or `.none`. |
| `referralId` | `String?` | The referral's id. `nil` for `.none`. |
| `linkId`, `linkUrl` | `String?` | The link the referral came from. |
| `matchMethod` | `MatchMethod?` | How the referral was matched. |
| `isExact` | `Bool` | `true` when the match rests on exact evidence. |
| `matchConfidence` | `Double?` | The confidence of an estimated match. |
| `flags` | `[String]` | Reasons for review, for example `outside_window`. |
| `duplicateOf` | `String?` | For `.ignored`, the referral that holds the credit. |
| `updated` | `Bool` | `true` when this call replaced an estimate with an exact match. |
| `replayState` | `ReplayState?` | `.original` or `.replayed`. |

**Errors:** `.notConfigured`, `.networkError`, `.serverError`, `.invalidApiKey`, `.keyAppMismatch`. An empty or over-long `installerId` fails with `.serverError` and status code 400.

### readTether(completion:)

```swift
public static func readTether(
    completion: @escaping (Result<TetherReadResult, WarpLinkError>) -> Void
)
```

Reads a Tether code from the clipboard now and sends it to the server. It works in every `tetherReadMode`. iOS may show its paste prompt, and the person can refuse it. Only text that is a WarpLink code is sent. `completion` is always called on the main queue.

**Results:** `.success(.matched(link))`, `.success(.noCode(reason))`, `.success(.unusable)` and `.success(.test(receipt:))`. See [TetherReadResult](#tetherreadresult). **Errors:** `.notConfigured` before `configure`, and a refused code, for example one that is invalid or expired, and a network error. See [Tether](https://warplink.app/docs/tether/sdk-modes).

### clearAttribution()

```swift
public static func clearAttribution() -> Result<Void, WarpLinkError>
```

Forgets this install's attribution so you can test a first launch again without deleting the app: the cached match, the attempt and completed markers, and any held referral invitation. Only the device is cleared. Server records are not deleted.

Test only. With a `wl_live_` key this does nothing and returns `.success`, so it never erases a live install's attribution. With a `wl_test_` key and `autoDeferredCheck` on, a check already in flight is discarded and a new check starts. A match from it reaches `onLink`.

**Errors:** `.notConfigured` before `configure`. `.decodingError` with the message "Could not clear stored attribution data." when a stored item could not be deleted and some state may remain. Calling again is safe.

---

## WarpLinkOptions

```swift
public struct WarpLinkOptions: Sendable
```

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `apiEndpoint` | `String` | `"https://api.warplink.app/v1"` | API endpoint URL. |
| `debugLogging` | `Bool` | `false` | Enable `[WarpLink]` console logging. |
| `autoDeepLinkHandling` | `Bool` | `true` | Automatically resolve forwarded Universal Links and dispatch to `onLink`. |
| `autoDeferredCheck` | `Bool` | `true` | Automatically run the deferred deep link check on first launch. |
| `linkDomains` | `[String]` | `[]` | Extra hosts the SDK should treat as yours, for links served from a custom domain. |
| `tetherReadMode` | `TetherReadMode` | `.pasteButton` | How the SDK reads a Tether code from the clipboard. See [TetherReadMode](#tetherreadmode). |
| `onLink` | `(@MainActor @Sendable (Result<WarpLinkDeepLink?, WarpLinkError>) -> Void)?` | `nil` | Single callback for cold start, warm start, and deferred results. Disambiguate with `isDeferred`. |

**From SDK 1.4.0,** the `onLink` parameter of `init` is `@MainActor`, so a handler can call your own main-actor code and compile under Swift 6 without `MainActor.assumeIsolated`. The stored `options.onLink` property keeps its `@Sendable` type. Called from the main thread, it runs the handler at once. Called from another thread, it runs the handler on the main queue.

The match window is server-side (set per link in the dashboard), so there is no `matchWindowHours` option.

### linkDomains and the WarpLinkDomains plist key

`linkDomains` is additive, never a replacement. The SDK recognizes the union of `aplnk.to`, `linkDomains`, the `WarpLinkDomains` string array in `Info.plist`, and the domains returned by `/sdk/validate`. The first three are known synchronously at `configure()`, so `open(_:)` claims a custom-domain link on the first launch instead of waiting for the server.

Entries are normalized: trimmed, lowercased, and reduced to a host if a full URL is given. A port is dropped, because the host of an incoming URL never carries one. Empty entries are dropped. A `www.` prefix is preserved, since it is a different host.

`WarpLinkDomains` is an array of strings. A single comma separated string is accepted too, because that is the row type Xcode's plist editor creates by default.

---

## DeferredCheckStatus

```swift
public enum DeferredCheckStatus: Equatable, Sendable
```

Where the deferred check stands for this install. Read it with `WarpLink.deferredCheckStatus`. It sends no request. Every state except `.checking` comes from what the SDK stored, so a relaunch keeps it.

| Case | Meaning |
|------|---------|
| `.notChecked` | No check has finished for this install. A failed check whose wait has passed also reads `.notChecked`, and the next one may send. |
| `.checking` | A check is running, or waiting for the app to come to the foreground. |
| `.matched` | The check finished and found a link. |
| `.noMatch` | The check finished and the server found no link. |
| `.waiting(retryAt: Date)` | An earlier check failed. The SDK sends nothing before `retryAt`. |
| `.skippedOldInstall` | The install is older than 30 days by default, so no request is sent. |
| `.stopped` | The SDK gave up 3 days after the first failure by default. No request is sent. |

A `wl_test_` key never reports `.waiting`, `.skippedOldInstall` or `.stopped`. With `debugLogging` on, the SDK prints `[WarpLink] Deferred check request: attempt <n>, raw signals <yes|no>` for each request, and `[WarpLink] Deferred check: <state>` when a check ends. A waiting check prints `Deferred check: waiting, retry at <ISO 8601 time>`. See [If your test did not match](https://warplink.app/docs/sdks/ios/deferred#if-your-test-did-not-match).

---

## TetherReadMode

```swift
public enum TetherReadMode: String, Sendable, CaseIterable
```

| Case | Meaning |
|------|---------|
| `.pasteButton` | The default. The person taps the system paste control (`WarpLinkPasteButton` or `WarpLinkUIPasteButton`). The SDK never reads the clipboard by itself. |
| `.automatic` | The SDK reads the clipboard once during the first-launch check. iOS may show its paste prompt then. |
| `.onCall` | The SDK reads the clipboard only when your app calls `readTether(completion:)`. |

## TetherReadResult

```swift
public enum TetherReadResult: Sendable, Equatable
```

| Case | Meaning |
|------|---------|
| `.matched(WarpLinkDeepLink)` | The code led to a link. It is also cached as `attributionResult`. |
| `.noCode(TetherMissReason)` | No code was read, so nothing was sent. The reason goes with the next attribution request. |
| `.unusable` | A code was sent and the server did not use it, or it led to no link. Let the person continue. |
| `.test(receipt: String?)` | A test code reached the server. Nothing was recorded. The receipt is also in `lastTetherTestReceipt`. |

`TetherMissReason` has the cases `pasteNotAllowed`, `clipboardEmpty`, `inAppBrowser`, `expired`, `otherApp`, `linkEnded` and `olderSdk`. This SDK reports `pasteNotAllowed`, `clipboardEmpty` and `olderSdk`. The server sets the others.

## WarpLinkPasteButton

```swift
public struct WarpLinkPasteButton: View
```

The SwiftUI paste button, iOS 16 and later. It wraps the system paste control. `init(onResult:onTether:)` reports each tap as a `TetherReadResult` in `onTether`. `init(onResult:)` accepts a referral invitation or a Tether code and reports the result as a `Result<WarpLinkDeepLink?, WarpLinkError>`, and every 1.3.0 call shape compiles unchanged. `WarpLinkUIPasteButton` is the UIKit view with the same `onResult` and `onTether` properties. See [Tether](https://warplink.app/docs/tether/sdk-modes).

---

## WarpLinkDeepLink

```swift
public struct WarpLinkDeepLink
```

| Property | Type | Description |
|----------|------|-------------|
| `linkId` | `String` | Unique link identifier. |
| `destination` | `String` | Resolved destination URL. |
| `deepLinkUrl` | `String?` | iOS-specific deep link URL (e.g., `myapp://path`). |
| `customParams` | `[String: JSONValue]` | The query parameters of the link's destination URL on a direct open, empty on a deferred match. Read values with the typed accessors (`.stringValue`, `.intValue`, `.doubleValue`, `.boolValue`). |
| `isDeferred` | `Bool` | Whether resolved via deferred attribution. |
| `matchType` | `MatchType?` | `.deterministic` or `.probabilistic`. |
| `matchConfidence` | `Double?` | Confidence score (0.0–1.0). Use it for reporting. |
| `matchGuaranteed` | `Bool` | True only for an exact match, including an invitation token match. Use it to pick a destination, and keep sign-in on your own authentication. |
| `attributionId` | `String?` | A stable id for this attribution. Send it to your backend to claim from there. |
| `matchMethod` | `MatchMethod?` | `.installToken`, `.androidReferrer`, `.referrer`, `.deviceId`, `.linkOpen` or `.probabilistic`. `.referrer` is a plain link ID from the Play install referrer. `nil` for a value this SDK does not know. |
| `evidenceClass` | `EvidenceClass?` | `.exact`, `.estimated` or `.legacyLink`. `nil` is never read as exact. |
| `replayState` | `ReplayState?` | `.original` for the first answer, `.replayed` for a repeat. |
| `capturedParams` | `[String: JSONValue]` | The allowed parameters captured when the link was tapped. Empty when there are none. |
| `tappedAt` | `String?` | When the link was tapped, as the server wrote it. |

Access custom params with the typed accessors:

```swift
if let productId = deepLink.customParams["product_id"]?.stringValue {
    showProduct(id: productId)
}
```

---

## JSONValue

```swift
public enum JSONValue: Codable, Sendable, Equatable
```

The value type of `customParams`, which the API returns as a JSON object. Read a value with its typed accessor rather than switching on the enum cases directly.

| Accessor | Type | Description |
|----------|------|-------------|
| `stringValue` | `String?` | The value if it is a JSON string. |
| `intValue` | `Int?` | The value if it is a JSON number representable as an `Int`. |
| `doubleValue` | `Double?` | The value if it is a JSON number. |
| `boolValue` | `Bool?` | The value if it is a JSON boolean. |
| `arrayValue` | `[JSONValue]?` | The value if it is a JSON array. |
| `objectValue` | `[String: JSONValue]?` | The value if it is a JSON object. |
| `foundationValue` | `Any` | The value lowered to a Foundation/JSON object graph (`String`/`Int`/`Double`/`Bool`/`[String: Any]`/`[Any]`/`NSNull`). |

---

## MatchType

```swift
public enum MatchType: String, Codable, Sendable
```

| Case | Description |
|------|-------------|
| `.deterministic` | Resolved straight from a tapped link, or matched by the Play Install Referrer on Android. Confidence is always 1.0. A deferred install on iOS is deterministic only when it is matched by a referral invitation token. |
| `.probabilistic` | Matched via enriched match key. |

---

## WarpLinkError

```swift
public enum WarpLinkError: Error, LocalizedError
```

| Case | Description |
|------|-------------|
| `.notConfigured` | SDK used before `configure()`. |
| `.invalidApiKeyFormat` | Key format invalid (`wl_live_` or `wl_test_` + 32 chars). |
| `.invalidApiKey` | Key rejected by server. |
| `.keyAppMismatch` | The key is valid but tied to a different app. Use the SDK key created for this app. |
| `.networkError(Error)` | Network request failed. |
| `.serverError(statusCode: Int, message: String)` | API error response. |
| `.invalidURL` | Not a recognized WarpLink domain. |
| `.linkNotFound` | Link not found or inactive. |
| `.passwordRequired` | Link is password protected, so it resolves to no destination and no platform URLs. |
| `.decodingError(Error)` | Response parsing failed. `clearAttribution()` also fails with it, with the message "Could not clear stored attribution data.", when a stored item could not be deleted. |

---

## WarpLinkAppDelegate

```swift
open class WarpLinkAppDelegate: UIResponder, UIApplicationDelegate
```

Drop-in `UIApplicationDelegate` that forwards Universal Links to WarpLink. Use it directly, or subclass it and copy the two forwarding calls into your own delegate. No method swizzling is performed.

| Member | Description |
|--------|-------------|
| `application(_:continue:restorationHandler:)` | Forwards the incoming `NSUserActivity` to `WarpLink.continue(_:)`. |
| `application(_:open:options:)` | Forwards the incoming URL to `WarpLink.open(_:)`. |

## WarpLinkSceneDelegate

```swift
open class WarpLinkSceneDelegate: UIResponder, UIWindowSceneDelegate
```

Drop-in `UIWindowSceneDelegate` that forwards Universal Links to WarpLink, covering cold launch, warm continue, and URL contexts.

| Member | Description |
|--------|-------------|
| `window` | `UIWindow?`, the scene's window. |
| `scene(_:willConnectTo:options:)` | Forwards the connection options' user activities and URL contexts to `WarpLink.continue(_:)` and `WarpLink.open(_:)` on cold launch. |
| `scene(_:continue:)` | Forwards the incoming `NSUserActivity` to `WarpLink.continue(_:)` on warm continue. |
| `scene(_:openURLContexts:)` | Forwards each incoming URL context to `WarpLink.open(_:)`. |

## Thread Safety

- `isConfigured` is thread-safe (protected by `NSLock`)
- All completion handlers are dispatched to the **main thread**
- `configure()` can be called from any thread. Call it once at startup. A repeat call with the same key and options keeps the running session and only replaces `onLink`
