iOS (Swift)
Universal Links, custom-scheme hand-offs and deferred links for native iOS. No clipboard by default.
On this page 8
One prompt · for your AI coding tool
Add Strait deep links (and deferred deep links) to this iOS app.
Read https://straitlink.in/docs/sdks/ios/ and follow it exactly. If anything here disagrees with that page, the page wins.
My link domain is https://<your-handle>.strait.link and my publishable key is st_pub_live_… (from Dashboard → Setup → Your keys: https://app.straitlink.in/setup#keys).
Rules:
- Use only the publishable key here. Never put a secret key (st_live_…) in app or website code.
- Route every link from the SDK's onLink callback (the event's path and params). Do not add a second deep-link handler for the link domain.
- iPhone links are live; install matching after an App Store install is opt-in (an Estimated match): tell me which parts need it switched on. With scenes, pass the launch URL to start(initialURL:).
Steps:
1. Install the SDK with the command on that page.
2. Let the phone open the app: the Associated Domains capability applinks:<your-handle>.strait.link, and my custom scheme under URL Types.
3. Create the client once with publishableKey and endpoint, call start() once at launch, and subscribe to onLink.
4. Map link paths to screens in this codebase.
Finish by telling me exactly how to check it:
- curl https://<your-handle>.strait.link/.well-known/assetlinks.json and /.well-known/apple-app-site-association list my app
- a tap from WhatsApp on a real phone opens the right screen and onLink fires with matched: trueBy hand · the install line
.package(url: "https://github.com/strait-link/strait-sdk-swift", from: "0.11.7")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:
.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.
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
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
@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.
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.
Deferred match only
Without the client, for an app that only wants the first-launch match:
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
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 nowThe 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.)
links.setUserId(user.id) // after sign-in, and at launch when already signed in
links.setUserId(nil) // on sign-outLater trackEvent calls carry the id to your app.event webhook 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+or00(+91 98765 43210→+919876543210), else of its digits. The webhook then hasuserIdHashed: 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). - 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.linkis missing from Associated Domains, or your Apple Team ID and bundle ID aren't saved in Dashboard → Apps & stores, soapple-app-site-associationdoesn't name your app. iOS caches that file through Apple's CDN, so a fix can take a while to show. More in Troubleshooting. matchedisfalse. Readreason:not_found(wrong slug or another workspace's key),expired,password_protected(password links can't open in the app), ornetwork(no answer; the open is saved and sent later). All reasons.- 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.checkDeferredwhile debugging. appStateis neverclosedwith SwiftUI. SwiftUI delivers the launch link throughonOpenURL. Use a scene delegate andstart(initialURL:), as above.