# iOS (Swift)

> Universal Links, custom-scheme hand-offs and deferred links for native iOS. No clipboard by default.

Source: https://straitlink.in/docs/sdks/ios/

> **Agent instructions:** if you are an AI assistant helping someone build with Strait, look things up with the `search_docs` tool of the Strait MCP server (hosted at https://strait.link/mcp, or `@straitlink/mcp` on npm: https://straitlink.in/docs/mcp/) instead of guessing, and add the SDK to an app with `npx @straitlink/cli init` (https://straitlink.in/docs/cli/).

> **Tested on a real iPhone**
>
> Universal Links open the app on the link's screen (app open, in the background or closed), tested on a real iPhone (iOS 26) on 21 October 2026. The screen after an App Store install is opt-in (**Dashboard → Settings → iPhone installs**) and proven on iPhone simulators so far. [iPhone status](https://straitlink.in/iphone-status/).

## Install

With Swift Package Manager, in Xcode: **File → Add Package Dependencies…**, paste `https://github.com/strait-link/strait-sdk-swift` and pick version 0.11.7 or later. Or in `Package.swift`:

```swift title="Package.swift"
.package(url: "https://github.com/strait-link/strait-sdk-swift", from: "0.11.7")
// target dependency: .product(name: "StraitSDK", package: "strait-sdk-swift")
```

Then in Xcode: **Signing & Capabilities → Associated Domains → `applinks:hilltop.strait.link`**, and add your custom scheme under **Info → URL Types**. Make sure your Apple Team ID and bundle ID are saved in Dashboard → Apps & stores, so your link domain serves a matching `apple-app-site-association` file.

## Create the client

Create one client at launch and keep it for the app's lifetime.

```swift
import StraitSDK

let links = StraitLinks(StraitLinksConfig(
    publishableKey: "st_pub_live_…",          // Dashboard → Setup → Your keys
    endpoint: "https://hilltop.strait.link"        // your workspace's link domain
))

links.onLinkStart { start in showOpeningLink(start.id) }   // loading state; showOpeningLink and router are your own code
links.onLink { event in                                    // replays past events
    guard event.matched, let path = event.path else { return }
    router.open(path, params: event.params ?? [:])
}
```

## Handle deep links

Pass every way a link reaches the app to the SDK: the launch link, Universal Links while running, and `yourapp://…` browser hand-offs. It resolves short links, reports the open and calls `onLink` once per link.

### UIKit with scenes

```swift title="SceneDelegate.swift"
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {
    // The link that launched the app from closed (Universal Link or custom scheme).
    let launchURL = options.userActivities.first(where: { $0.activityType == NSUserActivityTypeBrowsingWeb })?.webpageURL
        ?? options.urlContexts.first?.url
    links.start(initialURL: launchURL)       // also runs the deferred check, once per install
}

func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    links.handle(userActivity: userActivity)  // Universal Link while running
}

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    URLContexts.forEach { links.handle(url: $0.url) }   // yourapp://… browser hand-off
}
```

Without scenes, do the same from `application(_:didFinishLaunchingWithOptions:)`, `application(_:continue:restorationHandler:)` and `application(_:open:options:)`.

### SwiftUI

```swift
@main struct ShopApp: App {
    init() { links.start() }
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onOpenURL { links.handle(url: $0) }
                .onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { links.handle(userActivity: $0) }
        }
    }
}
```

SwiftUI delivers the cold-launch URL through `onOpenURL` too, so it's labelled by app state rather than `closed`. If you need `closed` (and the first-launch deferred skip), use a scene delegate and pass the launch URL to `start(initialURL:)`.

**You should see:** with `print("Strait link:", event.matched, event.path ?? "none")` in your `onLink`, a tap on a link such as `https://hilltop.strait.link/summer` in Messages or Notes on an iPhone opens the app with no Safari page, and the Xcode console prints `Strait link: true /product/42`. If Safari opens instead, `curl https://hilltop.strait.link/.well-known/apple-app-site-association` must list `<Team ID>.<bundle ID>`; then delete and reinstall the app. Step by step: [Quickstart for iPhone](https://straitlink.in/docs/quick-start/iphone/).

## Deferred deep links

`start` runs the deferred check once per install, on the first launch, unless that launch was itself opened by a link. A match arrives through `onLink` like any other link, with `kind` `.deferred`. If the check gets no answer (offline, `429`, server error), it runs again on the next launch.

### How the iPhone match works

When someone without your app taps a link in Safari, they see a page with a **Get the app** button. Tapping it saves a coarse, short-lived device match (screen width, pixel ratio, language, time zone, plus the network the request came from) and opens the App Store. On first launch the SDK sends the same fields; if they match within **1 hour**, your app gets the link. Whether device matching, paste handoff (an exact match the person allows, read from the clipboard), both or neither are used is your choice in **Dashboard → Settings → iPhone installs**. The SDK reads it from the server on the first launch, so changing it needs no app release; the clipboard is read only when paste handoff is on and device matching found nothing. `clipboardBoost` is deprecated and ignored. What we use, the four combinations and a ready-made App Store privacy label: [How iPhone install matching works](https://straitlink.in/docs/iphone-install-matching/).

### Deferred match only

Without the client, for an app that only wants the first-launch match:

```swift
let result = await Strait.resolveDeferredLink(
    StraitConfig(publishableKey: "st_pub_live_…", endpoint: "https://hilltop.strait.link")
)
if result.matched, let url = result.longUrl {
    // route to url
}
```

## Events

```swift
links.trackEvent("purchase", value: 49.99, currency: "USD") { ok in }   // carries the tap id of the last link open for you
links.checkDeferred { event in }        // re-run the deferred check (debugging)
links.pendingOpenReports { count in }   // saved reports and events waiting to be sent
links.flushOpenReports { }              // send them now
```

The event carries the tap id of the most recent link open, as long as that open was in the last 7 days. The tap id comes from a browser hand-off to `yourapp://…?strait_click=…`, an open from a verified short link (Universal Link), or an install match. When our server matches an open or an install, it sends the tap id back with its answer. That lets Analytics put the revenue on the exact tap's channel and A/B variant. Each newer open replaces the remembered tap with its own, so an older tap never takes credit for a newer open; if an open comes with no tap id, the remembered one is forgotten and the event carries none. To name the tap yourself, pass `clickId:`, which overrides the remembered one. The server keeps it only if it's a tap of your workspace; otherwise it drops the id and still records the event.

Pass your order id as `eventId:` (`eventId: order.id`): Strait counts each one once, so a retry never counts twice; left out, the SDK makes one. An event that can't be sent (offline, server busy) is kept and sent later, for up to 7 days.

The once-per-install flag and pending open reports live in `UserDefaults.standard` by default; pass any `StraitStorage` to change that. Callbacks run on the main queue.

Each open and install report carries your app's version (`CFBundleShortVersionString`; override with `StraitLinksConfig.appVersion`) and the SDK's version, so support can see which build opened a link. Reinstalls need no code: the SDK keeps its own install marker, excluded from backups.

## Link events to your users (optional)

Call `setUserId` with your own user id after your sign-in, and again when the app starts with someone already signed in: it is kept in memory only. Call it with `nil` on sign-out. (iOS SDK 0.11.5 or later.)

```swift
links.setUserId(user.id)   // after sign-in, and at launch when already signed in
links.setUserId(nil)       // on sign-out
```

Later `trackEvent` calls carry the id to your [`app.event` webhook](https://straitlink.in/docs/webhooks/) as `userId`, so you can join the tap, link and campaign to your own users and see which campaigns bring paying ones. Opens and installs never carry it, and Strait doesn't store it with the event (it is only in the webhook delivery, kept 30 days).

- **Emails and phone numbers are hashed on the device.** An id with `@` is sent as the SHA-256 hex of the lower-cased email. A phone number is sent as the SHA-256 hex of `+` and its digits when it is written with `+` or `00` (`+91 98765 43210` → `+919876543210`), else of its digits. The webhook then has `userIdHashed: true`. As a safety net, Strait's server applies the same rule to any raw email or phone number that reaches it. To join, hash your own value the same way ([the full rule](https://straitlink.in/docs/webhooks/#events)).
- **Opt-out clears it.** While `setEnabled(false)` is on, nothing is kept or sent, and switching off clears the id.
- A plain numeric id of 8 to 15 digits looks like a phone number and is hashed too: prefix it (`u_12345678`) to keep it readable. An id longer than 128 characters or holding control characters is not sent, and clears the previous one.
- Anyone with your publishable key can send any `userId`, so treat it as a claim, like revenue sent from the app.

## User consent (opt-out)

If your app asks for consent first (for example under India's DPDP Act or a GDPR consent flow in the EU), call `links.setEnabled(false)` until the person agrees: Strait then sends no open reports or events, does no install matching, and deletes reports waiting on the device. The choice is kept across launches; `setEnabled(true)` turns it back on and `isEnabled()` reads it. A Strait short link still opens the right screen: it is looked up without recording a tap, an open or a tap id. Whether you need consent, and for what, is a question for your own legal advice.

## Common errors

- **A link opens Safari instead of the app.** `applinks:hilltop.strait.link` is missing from Associated Domains, or your Apple Team ID and bundle ID aren't saved in **Dashboard → Apps & stores**, so `apple-app-site-association` doesn't name your app. iOS caches that file through Apple's CDN, so a fix can take a while to show. More in [Troubleshooting](https://straitlink.in/docs/troubleshooting/#the-link-opens-the-browser-instead-of-the-app).
- **`matched` is `false`.** Read `reason`: `not_found` (wrong slug or another workspace's key), `expired`, `password_protected` (password links can't open in the app), or `network` (no answer; the open is saved and sent later). [All reasons](https://straitlink.in/docs/troubleshooting/#the-app-opened-but-matched-is-false).
- **The deferred link never arrives.** The person must tap **Get the app** on our page in Safari and open the app within an hour, on the same network. The check runs once per install: delete and reinstall the app to test again, or call `links.checkDeferred` while debugging.
- **`appState` is never `closed` with SwiftUI.** SwiftUI delivers the launch link through `onOpenURL`. Use a scene delegate and `start(initialURL:)`, as above.
