
# iOS SDK

`KerdlySDK` measures installs, users, events and purchases in a native iOS app and sends them to
your Kerdly project. Kerdly matches each install to the ad that brought it, then to the revenue
the App Store reports. Swift, no third-party dependencies, open source:
[github.com/Kerdly/kerdly-sdk](https://github.com/Kerdly/kerdly-sdk/tree/main/ios).

Building with Expo or React Native? Use the [Expo SDK](https://kerdly.com/docs/sdks/expo.md) instead: it carries this
same iOS code.

## Requirements

- iOS 15 or newer, Swift 5.9 or newer, Xcode with Swift Package Manager.
- The app's iOS app in your Kerdly project. The product form at sign-up makes it when you tick
  **iOS app**; with its App Store ID, purchases and installs line up with App Store Connect.

## Before you start

Open the iOS app's **Settings → SDK** in the dashboard. Its **app key** (`pk_live_…`) is already
made and shown in the code to paste. App keys are public; they ship inside your app. Use a
`pk_test_…` key for test builds, so their traffic stays out of your reports. Never put a server key
(`sk_…`) in the app; the SDK refuses it.

Each app key belongs to one bundle id. The SDK sends it with every request, and Kerdly refuses a
key used by another app.

## Install

In Xcode: **File → Add Package Dependencies…**, enter `https://github.com/Kerdly/kerdly-sdk`,
choose **Up to Next Minor Version** from `0.1.0`, and add `KerdlySDK` to your app target.

In a `Package.swift`:

```swift
.package(url: "https://github.com/Kerdly/kerdly-sdk", .upToNextMinor(from: "0.1.0")),
// …
.product(name: "KerdlySDK", package: "kerdly-sdk")
```

The SDK is distributed through Swift Package Manager only, not CocoaPods. Until 1.0 a minor
version may change the API, so "Up to Next Minor" is the safe rule.

## Configure

Call `configure` once, as early as possible: in `application(_:didFinishLaunchingWithOptions:)`,
or your SwiftUI `App` initializer. It returns at once; the work happens in the background.

```swift
import KerdlySDK

@main
struct TallybirdApp: App {
    init() {
        Kerdly.configure(KerdlyOptions(key: "pk_live_…"))   // Tallybird iOS's app key
    }
    var body: some Scene { WindowGroup { ContentView() } }
}
```

```swift
// UIKit
func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    var options = KerdlyOptions(key: "pk_live_…")
    options.logLevel = .warn
    Kerdly.configure(options)
    return true
}
```

| Option | Default | |
|---|---|---|
| `key` | required | The app's public key: `pk_live_…`, or `pk_test_…` for test builds. |
| `endpoint` | `https://app.kerdly.com/api` | Change it only if Kerdly support asks you to. |
| `environment` | `.auto` | `.production`, `.sandbox` or `.development`. `.auto` detects it from the build. |
| `collectAdvertisingId` | `true` | Read the IDFA when the user allowed tracking. |
| `skanWriter` | `false` | Let Kerdly write SKAdNetwork conversion values. See [SKAdNetwork](#skadnetwork). |
| `logLevel` | `.warn` | `.none`, `.error`, `.warn`, `.info` or `.debug`. |

Every other method is safe from any thread, before or after `configure` (earlier calls run once the
SDK has started), and never throws.

## Users and consent

After sign-in, set your own user id; it is attached to every later event. Clear it on sign-out.
Use the same id your server and RevenueCat use.

```swift
Kerdly.setUserId(user.id)                      // after sign-in
Kerdly.setUserId(nil)                          // on sign-out
Kerdly.setConsent(analytics: true, ads: true)  // reflect your consent screen
```

- `analytics: false` stops your custom and standard events; installs and opens are still counted.
- `ads: false` stops reading the advertising identifier and other ad-measurement signals.

## Standard events

Send these at the moments ad networks optimize on. Every argument is optional.

```swift
Kerdly.trackRegistration(method: "apple")
Kerdly.trackStartTrial(productId: "tallybird_pro_weekly", value: 0, currency: "USD", transactionId: tx)
Kerdly.trackSubscribe(productId: "tallybird_pro_weekly", value: 7.99, currency: "USD", transactionId: tx)
Kerdly.trackPurchase(productId: "streak_freeze_5", value: 4.99, currency: "USD", quantity: 1, transactionId: tx)
```

- `value` is what the user paid, in `currency` (`0` for a free trial).
- `currency` is a three-letter ISO 4217 code. A `value` without a valid currency is dropped.
- `quantity` is a whole number of 1 or more.
- `properties:` adds your own fields under the custom-event rules below.

These events tell the ad networks early. The revenue in your reports comes from the App Store
itself, so renewals and refunds need nothing from the app (see
[Client events, server events and deduplication](https://kerdly.com/docs/guides/events-and-dedupe.md)).

## Custom events

```swift
Kerdly.track("quiz_completed", properties: ["score": 42, "level": "hard"])
```

- Names and property keys: lowercase letters, digits and `_`, starting with a letter, at most 40
  characters.
- At most 25 properties. Values are strings (up to 256 characters), numbers or booleans.
- An invalid name drops the event; an invalid property is dropped on its own. With
  `logLevel = .debug` the console says why.

## Link purchases to the install

Renewals and refunds come from the App Store. To credit them to the right campaign, link each
purchase to the install:

1. Tell the SDK the `appAccountToken` your purchases carry (a UUID; with Superwall, the UUID in the
   user's alias).
2. After each completed purchase, pass the transaction to `notifyPurchase`.

```swift
Kerdly.setAppAccountToken(accountTokenUUID)

// in your purchase callback (StoreKit 2 Transaction)
Kerdly.notifyPurchase(KerdlyPurchase(originalTransactionId: String(tx.originalID),
                                     transactionId: String(tx.id),
                                     productId: tx.productID,
                                     appAccountToken: tx.appAccountToken))

// after a restore, with no argument: links the current entitlements
Kerdly.notifyPurchase()
```

Each transaction is linked once; calling it again is harmless. For the whole store setup (App Store
Connect, real-time notifications), see [Sell in a store app](https://kerdly.com/docs/guides/store-app.md).

If your app also sends conversions to Meta or TikTok itself, record each send with the event id the
network receives, so Kerdly can show both sides:

```swift
Kerdly.recordNetworkSend(KerdlyNetworkSend(network: "meta", event: "StartTrial",
                                           eventId: eventId, value: 0, currency: "USD"))
```

Ids from other SDKs can be attached with `Kerdly.setPartnerIds(["superwall_alias": alias])`.

## Deep links

Pass every URL your app is opened with to `Kerdly.handleUrl`. It records the open and returns the
Kerdly parameters it found; your app keeps its own navigation. Custom schemes and universal links
both work, including [Kerdly links](https://kerdly.com/docs/guides/web-to-app.md).

```swift
// SwiftUI
.onOpenURL { Kerdly.handleUrl($0) }

// UIApplicationDelegate
func application(_ app: UIApplication, open url: URL,
                 options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    Kerdly.handleUrl(url)
    return true
}

// UISceneDelegate
func scene(_ scene: UIScene, willConnectTo session: UISceneSession,
           options connectionOptions: UIScene.ConnectionOptions) {
    connectionOptions.urlContexts.forEach { Kerdly.handleUrl($0.url) }
    connectionOptions.userActivities.compactMap(\.webpageURL).forEach { Kerdly.handleUrl($0) }
}
func scene(_ scene: UIScene, openURLContexts contexts: Set<UIOpenURLContext>) {
    contexts.forEach { Kerdly.handleUrl($0.url) }
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    if let url = userActivity.webpageURL { Kerdly.handleUrl(url) }
}
```

`handleUrl` returns a `KerdlyDeepLink` (`url`, `cpp`, `ppid`, `clickId`, `visitId`, `campaignIds`) or
nil.

## Attribution

```swift
Kerdly.onAttribution { attribution in
    // on the main thread: now if known, and again if it changes
    print(attribution.network, attribution.campaign ?? "")
}

let current = Kerdly.attribution   // nil until known
let installId = Kerdly.installId   // give it to your backend to tie accounts to installs
```

`Kerdly.flush()` sends queued events now, for example before a UI test ends.

## App Tracking Transparency

The SDK never shows the tracking prompt on its own. To ask:

```swift
let status = await Kerdly.requestTrackingAuthorization()
```

Add `NSUserTrackingUsageDescription` to your Info.plist first; without it the SDK doesn't ask and
returns the current status. The prompt appears once the app is active, and the answer is recorded.

## SKAdNetwork

Keep your `SKAdNetworkItems`, and `NSAdvertisingAttributionReportEndpoint` if you receive postback
copies, in Info.plist. To have Kerdly write conversion values, set `options.skanWriter = true`.
Only one SDK in an app should write conversion values, so turn off any other writer in the same
release.

## Data and privacy

What the SDK sends, for your App Store privacy answers:

| Data | When |
|---|---|
| An install id generated by the SDK, and the IDFV | always |
| Device model, OS version, language, time zone, app version | always |
| Apple Ads attribution token and the App Store's install record (AppTransaction) | once per install |
| App events you track | with `analytics` consent |
| Purchase identifiers | when you call `notifyPurchase` |
| IDFA | only with tracking authorized, `ads` consent and `collectAdvertisingId` |
| Public IPv6 address | with `ads` consent |
| The user id you set | when you call `setUserId` |
| The IDFA (when allowed), sent to Meta and TikTok to ask which ad led to the install | only with deferred deep links on in your Kerdly project, and `ads` consent |

The SDK never collects names, email addresses, phone numbers or clipboard contents, and never reads
location services (GPS). It ships a privacy manifest (`PrivacyInfo.xcprivacy`) that Xcode adds to
your app's privacy report.

## Check it's working

1. Set `options.logLevel = .debug` and run the app on a device or simulator.
2. Filter the Xcode console for `[Kerdly]`: the SDK logs what it sends and any error Kerdly answers
   with.
3. In the dashboard, the iOS app's **Onboarding** page shows the SDK step with the time of the last
   event. Events arrive within a minute; `Kerdly.flush()` sends at once.

## Troubleshooting

- Kerdly answers `bundle_mismatch`: the key belongs to another Kerdly app, or the bundle id doesn't
  match this app's.
- Kerdly answers `bad_key` or `key_revoked`: the key was mistyped or revoked; create a new one under
  **Settings → SDK**.
- Questions or problems: [open an issue](https://github.com/Kerdly/kerdly-sdk/issues) or contact
  Kerdly support. Never post your keys.

## Agent checklist

- [ ] `KerdlySDK` added with Swift Package Manager, up to the next minor version from `0.1.0`.
- [ ] `Kerdly.configure` once at launch, with the iOS app's `pk_live_` key (never an `sk_` key).
- [ ] `setUserId` after sign-in and `nil` on sign-out, with the id your server uses.
- [ ] `trackRegistration` on sign-up; `trackStartTrial`, `trackSubscribe` or `trackPurchase` from the
      purchase flow, with `productId`, `value`, `currency` and `transactionId`.
- [ ] `setAppAccountToken` and `notifyPurchase` for every App Store purchase.
- [ ] `handleUrl` for every URL the app opens with (scene delegate, app delegate or `.onOpenURL`).
- [ ] Existing analytics and attribution SDKs left in place.

---

Source: https://kerdly.com/docs/sdks/ios. Index of all docs: https://kerdly.com/llms.txt
