Skip to main content

iOS SDK

Native iOS SDK for deep linking, mobile attribution, and conversion tracking.

Faster setup with AI

Using Claude Code, Cursor or Codex? Copy this prompt and paste it into your agent from the root of your project. It installs the SDK, wires deep links through your navigation (asking you which screen each link should open), adds one event, and verifies the install in your LinkForty dashboard.

Install the LinkForty SDK in a native iOS app
Swift SDK via Swift Package Manager, Universal Links, deferred and direct deep links, and a first in-app event.
Show the prompt
I use LinkForty (https://linkforty.com), a deep-linking and mobile attribution platform: short links that route each click to the app, the app store or the web, and record clicks, installs and in-app events per link.

Before writing any code, read the LinkForty documentation index at https://docs.linkforty.com/llms-full.txt and the pages listed under "Docs" below. Work from what the docs say, not from assumptions about how similar products work. If something you need is not in the docs or in this prompt — an ID, a token, a URL — stop and ask me for it rather than inventing a placeholder that looks real.

## Task: install the LinkForty iOS SDK

Add the LinkForty SDK to this app so that an install that follows a click on one of my links is attributed to that link, a link's deep-link path opens the right screen on first launch (deferred deep linking) and on later opens (Universal Links / App Links), and one key in-app event is recorded.

## Values

- **App token**: shown in the LinkForty dashboard under Workspace Settings → App Token (it starts with `at_`). Ask me for it; put it in the app's config or environment, not hard-coded in a committed source file.
- **Base URL**: `https://api.linkforty.com` for LinkForty Cloud. (Only a self-hosted LinkForty server uses a different origin — ask if you are not sure which this is.)
- **Link host**: the host my links are on, shown in the dashboard under Settings → Domains — the workspace's own host (it looks like `something.toapp.me`) and any verified custom domain listed there. Ask me for it. This is the domain the app must claim for Universal Links / App Links.
- **LinkForty MCP server** (optional): if it is configured in this environment (https://mcp.linkforty.com/mcp, or the `linkforty-mcp` command), use `get_app_config` to read the workspace's app settings and `create_link` to make a test link at the end. Do not set it up for me if it is not.

## How to work

1. **Look before you change anything.** Identify the framework, its version, the navigation/router library and where the app initializes at launch. List the screens (routes) you found, and **ask me which screen each incoming link should open and what parameter it needs** — for example "a link with `productId` opens the product screen". Wait for my answer before editing; do not guess routes.
2. **Work on a new git branch.** If the working tree has uncommitted changes, stop and tell me instead of building on top of them.
3. **Follow the docs pages named below, not memory.** Package names, method names and config keys come from those pages; LinkForty's SDKs are not the same as other attribution SDKs you may know.
4. **Do not invent values.** Anything in "Values" that says "ask me" is something you ask for. Never commit a token to source.
5. **Keep the app working without a link.** A launch with no matching click must behave exactly as before: no crash, no error surfaced to the user, no blocked start-up.
6. **Finish with a summary**: every file you changed and why; the manual steps that remain for me (Apple Team ID and bundle ID, Play signing SHA-256 fingerprint, store listing, a rebuild and reinstall) and where in the LinkForty dashboard each one goes (Workspace Settings → App Configuration); and anything you were unsure about.
7. **Verify.** Run the app once, then check the LinkForty dashboard: the SDK Doctor badge in the sidebar (https://docs.linkforty.com/guides/attribution/sdk-health) should report the SDK as installed. If the MCP server is available, create a test link with `create_link` and open it on a device or simulator; the click and the deep link should reach the screen we agreed on.

## Steps

1. **Install** the package `https://github.com/LinkForty/mobile-sdk-ios.git` (1.8.0 or later) with Swift Package Manager (the SDK is SPM-only; there is no CocoaPods pod or Carthage build) and `import LinkFortySDK` (https://docs.linkforty.com/sdks/ios#installation).
2. **Initialize once at launch** — in the `@main` App struct's `init` or `AppDelegate`: build a `LinkFortyConfig(baseURL:appToken:debug:)` with the base URL and app token from "Values" and call `try await LinkForty.shared.initialize(config:)` (https://docs.linkforty.com/sdks/ios#initialize-the-sdk). Leave `apiKey` out — it is only for creating links from the app. Initialization failure must be logged, never fatal.
3. **Claim the link host** (https://docs.linkforty.com/sdks/ios#universal-links-setup): add the Associated Domains capability with `applinks:<link host>` (one entry per host if there is also a custom domain). LinkForty serves the apple-app-site-association file on that host itself; nothing to upload. Tell me the Apple Team ID and bundle ID must be entered in LinkForty under Workspace Settings → App Configuration, or Universal Links will not verify.
4. **Deferred deep link**: register `LinkForty.shared.onDeferredDeepLink { data in … }` right after initialize. When `data` is non-nil, route to the screen we agreed on using its `deepLinkPath` / `customParameters`; when it is nil (organic install) do nothing (https://docs.linkforty.com/sdks/ios#handle-deferred-deep-links).
5. **Direct deep links** (https://docs.linkforty.com/sdks/ios#handle-direct-deep-links): pass incoming URLs to `LinkForty.shared.handleDeepLink(url:)` — from SwiftUI `.onOpenURL`; in a UIKit app with a SceneDelegate from `scene(_:willConnectTo:options:)` (`connectionOptions.userActivities` / `urlContexts`, for a link that launches the app), `scene(_:continue:)` and `scene(_:openURLContexts:)`; in a UIKit app without scenes from `application(_:continue:restorationHandler:)` (`webpageURL`) and `application(_:open:options:)` — and register `LinkForty.shared.onDeepLink { url, data in … }` to route the same way through the app's existing navigation.
6. **One in-app event**: at the obvious success moment in this app (sign-up completed, purchase, or the first key action — tell me which you chose) call `trackEvent` with `signup`, or `trackRevenue` with amount and ISO currency for a purchase (https://docs.linkforty.com/sdks/ios#track-events). No personal data in properties.

## Docs

- iOS SDK: https://docs.linkforty.com/sdks/ios (Installation, Initialize the SDK, Handle Deferred Deep Links, Handle Direct Deep Links, Universal Links Setup, Track Events)
- SDK integration overview: https://docs.linkforty.com/guides/attribution/sdk-integration
- Deferred deep linking: https://docs.linkforty.com/guides/attribution/deferred-deep-linking
- Link hosts and app association files: https://docs.linkforty.com/guides/links/custom-domains#your-linkforty-domain
- SDK Doctor: https://docs.linkforty.com/guides/attribution/sdk-health

## Done when

- Opening one of my links on a device without the app, installing it and launching it lands on the screen we agreed on, and the install appears under Installs in the LinkForty dashboard attributed to that link.
- Opening the same link with the app installed goes straight to that screen without a browser stop.
- The in-app event shows under Events, attached to that install.
- SDK Doctor in the dashboard sidebar reports the SDK as installed.

When you are done, tell me: exactly which files changed and why, how I can verify it worked end to end (what to tap or run, and what I should see in the LinkForty dashboard), and anything you were unsure about.

It needs your app token; the prompt asks you for it, and the MCP server can supply it if you have that set up.

Features​

  • Deferred deep linking -- route new users to specific content after install
  • Direct deep linking -- handle Universal Links and custom URL schemes
  • Install attribution -- probabilistic fingerprint matching
  • Event tracking -- log in-app events tied to attribution data
  • Revenue tracking -- structured purchase tracking with dedicated method
  • Offline event queue -- events are kept on the device until the server has them, and a retry is stored once
  • Programmatic link creation -- create short links from your app
  • Zero external dependencies
  • Privacy-first -- no IDFA collection, includes Privacy Manifest

Requirements​

  • iOS 16.0+
  • Xcode 15.0+
  • Swift 5.9+

Installation​

In Xcode: File > Add Package Dependencies, then enter:

https://github.com/LinkForty/mobile-sdk-ios.git

Or add to your Package.swift:

dependencies: [
.package(url: "https://github.com/LinkForty/mobile-sdk-ios.git", from: "1.8.0")
]

The SDK is distributed with Swift Package Manager only; there is no CocoaPods pod or Carthage build.


Quick Start​

Initialize the SDK​

Initialize once at app launch, typically in your AppDelegate or @main App struct:

import LinkFortySDK

@main
struct MyApp: App {
init() {
Task {
let config = LinkFortyConfig(
baseURL: URL(string: "https://api.linkforty.com")!,
apiKey: "your-api-key", // optional -- required for link creation
appToken: "at_your_app_token", // required for Cloud: matches installs to your workspace's links only
debug: true,
attributionWindowHours: 168 // 7 days (default)
)
try await LinkForty.shared.initialize(config: config)
}
}

var body: some Scene {
WindowGroup {
ContentView()
}
}
}
LinkForty.shared.onDeferredDeepLink { deepLinkData in
if let data = deepLinkData {
print("Attributed install: \(data.shortCode)")
// Navigate to content based on custom parameters
if let productId = data.customParameters?["productId"] {
navigateToProduct(productId)
}
} else {
print("Organic install")
}
}

A deferred match is made from device signals, not an ID, so two people on the same network can be confused. The deferred deep link reports how the match was made: confidenceScore (0–100), matchedFactors, attributionMethod ("fingerprint") and competingLinks, the number of other links that had a click from the same network good enough to match. At 0 no other link was in contention. Above 0, another person's tap may be what led to this install, so before acting on a single-use link (a sign-in or gift link), ask the user to confirm. The fields are empty on a direct open, and from a server that doesn't report them. See Single-use links.

LinkForty.shared.onDeferredDeepLink { data in
guard let data else { return }
if (data.competingLinks ?? 0) > 0 {
confirmBeforeSignIn(data) // another link was in contention
} else {
signIn(data)
}
}

Pass every URL the app receives to handleDeepLink. With appToken set, the SDK learns your workspace's link hosts (its link host, verified custom domains and the platform short-link host) and looks up only URLs on them or on the baseURL host, answered only with your workspace's links; any other URL, custom schemes included, reaches onDeepLink as a local parse without a request. Without appToken, or until the hosts are known, every web URL is looked up.

The SDK does not observe incoming links itself: pass each URL to handleDeepLink from every entry point your app uses. A URL passed before initialize finishes is held until it does.

// SwiftUI: receives Universal Links and custom schemes, including the launch URL
.onOpenURL { url in
LinkForty.shared.handleDeepLink(url: url)
}

// UIKit with a SceneDelegate (the AppDelegate methods below are not called)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let url = connectionOptions.userActivities.first(where: { $0.activityType == NSUserActivityTypeBrowsingWeb })?.webpageURL {
LinkForty.shared.handleDeepLink(url: url)
}
if let url = connectionOptions.urlContexts.first?.url {
LinkForty.shared.handleDeepLink(url: url)
}
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else { return }
LinkForty.shared.handleDeepLink(url: url)
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url { LinkForty.shared.handleDeepLink(url: url) }
}

// UIKit without scenes: Universal Links
func application(_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else { return false }
LinkForty.shared.handleDeepLink(url: url)
return true
}

// UIKit without scenes: custom URL schemes
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
LinkForty.shared.handleDeepLink(url: url)
return true
}

Register a callback to receive the parsed data:

LinkForty.shared.onDeepLink { url, deepLinkData in
print("Deep link opened: \(url)")
if let data = deepLinkData {
if let route = data.customParameters?["route"] {
navigateToRoute(route)
}
}
}

Track Events​

// Custom event
try await LinkForty.shared.trackEvent(
name: "add_to_cart",
properties: ["productId": "123", "category": "electronics"]
)

// Revenue event
try await LinkForty.shared.trackRevenue(
amount: 29.99,
currency: "USD",
properties: ["productId": "123"]
)

Every event is automatically credited to the deep link that most recently opened the app (last-click attribution), along with an app-open session — so analytics can show what users do after clicking a link. Events with no preceding deep-link open are reported as organic. No extra code is required.

Track Screen Views​

Reporting screen views lets analytics build a per-link screen-flow funnel — which screens users reach after opening a deep link. Each screen_view carries the same last-click attribution as your other events.

SwiftUI — add the .linkfortyScreen(_:) modifier to a screen:

ProductView()
.linkfortyScreen("ProductDetail")

UIKit — call from viewDidAppear:

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Task { try? await LinkForty.shared.trackScreenView(name: "ProductDetail") }
}

You mark the screens you care about (there is no navigation swizzling), which keeps screen names meaningful; the SDK records the previous screen automatically so transitions appear in the funnel.

let result = try await LinkForty.shared.createLink(options: CreateLinkOptions(
deepLinkParameters: ["route": "PRODUCT", "id": "123"],
title: "Check out this product",
utmParameters: UTMParameters(source: "app", medium: "share")
))

print(result.url) // https://go.yourdomain.com/abc123
print(result.shortCode) // abc123
warning

Link creation requires an API key (without one, createLink throws missingApiKey) and works on LinkForty Cloud only: it uses the SDK link endpoint (/api/sdk/v1/links), which self-hosted Core doesn't have, and Core's own /api/links requires an originalUrl the SDK doesn't send.


  1. In Xcode, enable the Associated Domains capability
  2. Add your link host: applinks:acme.toapp.me for your LinkForty domain, and applinks:links.example.com for each custom domain
  3. Your LinkForty server automatically hosts the Apple App Site Association file at /.well-known/apple-app-site-association on every one of those hosts, once your Apple Team ID and bundle ID are set under Workspace Settings → App Configuration (self-hosted Core: the IOS_TEAM_ID and IOS_BUNDLE_ID environment variables; unset, the endpoint returns 404)

Example AASA format (served automatically by LinkForty):

{
"applinks": {
"apps": [],
"details": [{
"appID": "TEAM_ID.com.yourcompany.yourapp",
"paths": ["*"]
}]
}
}

API Reference​

Initialization​

MethodDescription
initialize(config:attributionWindowHours:deviceId:)Initialize the SDK and report the install (the last two are optional). Throws if the install can't be reported, e.g. offline; call it again later
isFirstLaunch()Whether this is the app's first launch since install

Deep Linking​

MethodDescription
onDeferredDeepLink(_:)Register callback for install attribution
onDeepLink(_:)Register callback for direct deep links
handleDeepLink(url:)Pass every incoming URL to the SDK; returns whether it was looked up as a LinkForty link

Event Tracking​

MethodDescription
trackEvent(name:properties:)Track a custom in-app event
trackRevenue(amount:currency:properties:)Track a revenue event
trackScreenView(name:properties:)Report a screen view (for screen-flow funnels)

SwiftUI apps can use the .linkfortyScreen("Name") view modifier instead of calling trackScreenView manually.

MethodDescription
createLink(options:)Create a short link programmatically

User Identity​

MethodDescription
setExternalUserId(_:)Set external user ID for share attribution (pass nil to clear)
getExternalUserId()Get the current external user ID

Data Access​

MethodDescription
getInstallData()Retrieve cached attribution data
getInstallId()Get the server-assigned install UUID

Event Queue​

MethodDescription
flushEvents()Manually send all queued events
clearEventQueue()Remove queued events without sending
queuedEventCountNumber of events waiting to be sent

Data Management​

MethodDescription
clearData()Wipe all locally stored SDK data
reset()Return SDK to uninitialized state

Offline Resilience​

Events that fail to send because of a network error or a server error are queued:

  • Maximum queue size: 100 events
  • The queue is saved on the device: an event is stored before it is sent and removed once the server has it, so events still queued when the app is closed are sent on a later launch
  • Queued events are sent after initialize(), when the app returns to the foreground, after the next event that sends successfully, or when you call flushEvents()
  • Each request is tried up to 3 times (1 s and 2 s pauses) before the event is left queued
  • trackEvent returns normally when the event is kept for later; it throws for an invalid event or one the server rejects (4xx)
  • When the queue is full, a new event that can't be sent is dropped without an error
  • Each event carries an id that stays the same on every retry, so a retry is stored once
  • Use flushEvents() to manually trigger a send
  • Use clearEventQueue() to discard queued events

Privacy​

The iOS SDK is designed with privacy in mind:

  • No IDFA, no ATT prompt, no SKAdNetwork -- deferred matching is probabilistic, from device signals and the network
  • Install ID -- the server assigns one on first launch; the SDK stores it on the device and sends it with every event
  • Privacy Manifest included -- declares no tracking, for App Store compliance
  • Data sent at install -- timezone, language, screen resolution, iOS version, app version, a user agent built from the app name and versions, the app token and SDK version (plus a deviceId only if your app passes one); link lookups send timezone, language, screen and iOS version; events send your event data with the install ID, a session ID and the last-opened link
  • HTTPS enforced -- all communication uses HTTPS (except localhost for development)

Self-Hosted Configuration​

For self-hosted LinkForty Core, point baseURL at your server. Core does not use appToken, and createLink is not available, so omit the API key:

let config = LinkFortyConfig(
baseURL: URL(string: "https://links.yourcompany.com")!,
apiKey: nil,
debug: false
)
try await LinkForty.shared.initialize(config: config)

Troubleshooting​

  1. Verify Associated Domains capability is enabled with the correct domain
  2. Check that the AASA file is accessible at https://go.yourdomain.com/.well-known/apple-app-site-association
  3. Long-press the link in Safari -- if "Open in App" appears, Universal Links are configured
  4. Apple caches AASA files; changes can take time to propagate
  1. Check debug logs (debug: true) for install reporting errors
  2. Ensure the attribution window hasn't expired
  3. Fingerprint matching depends on network conditions -- VPNs and privacy relays reduce accuracy

Build errors with SPM​

Ensure your project targets iOS 16.0+ and uses Xcode 15+.


Next Steps​

Resources​