> ## Documentation Index
> Fetch the complete documentation index at: https://docs.appstack.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Swift

<Prompt description="Use Cursor, Claude Code, or another AI to help you integrate the Swift SDK." actions={["copy", "cursor"]}>
  You are an expert iOS engineer helping me integrate the Appstack Swift SDK into my app. You are running inside an IDE assistant such as Cursor or Claude Code and you can see my codebase.

  Use the reference below to fully wire the SDK. When I paste this prompt and share my project files, you should:

  1. Determine the correct installation method and give me the **exact commands** (SPM / Xcode UI) using the package information below, pinning the dependency to the **latest stable release** from the repository (not an assumed old version).
  2. Tell me **exactly which files and functions** to edit (e.g. `AppDelegate` or the `@main` SwiftUI app) and propose ready-to-paste code that includes the Appstack `configure` call and any required imports, based on the snippets below.
  3. Before finalizing, restate the full checklist of steps you applied (install, configure, permissions, events) so I can confirm everything from the docs is covered.

  ***

  ## Reference: Appstack Swift SDK

  **Requirements**

  * iOS 13.0+
  * Xcode 14.0+
  * Swift 5.0+

  **Swift Package Manager**

  * Package URL: `https://github.com/appstack-tech/ios-appstack-sdk.git`
  * **Xcode:** File → Add Package Dependencies… → paste the URL → pick the **latest** stable version (or an appropriate range) from the package picker.
  * **Package.swift:** Add `.package(url: "https://github.com/appstack-tech/ios-appstack-sdk.git", from: "X.Y.Z")` where `X.Y.Z` is the **current** release from that repository’s releases/tags (refresh from GitHub when integrating).

  **Initialization examples**

  *AppDelegate*

  ```swift theme={null}
  import UIKit
  import AppTrackingTransparency
  import AppstackSDK

  @main
  class AppDelegate: UIResponder, UIApplicationDelegate {
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
          // Configure Appstack SDK
          AppstackAttributionSdk.shared.configure(
              apiKey: "your_api_key",
              isDebug: false,  // Set to true for development
              endpointBaseUrl: nil,
              logLevel: .info
          )

          // Request tracking permission and enable Apple Ads Attribution
          if #available(iOS 14.3, *) {
              ATTrackingManager.requestTrackingAuthorization { status in
                  AppstackASAAttribution.shared.enableAppleAdsAttribution()
              }
          }

          return true
      }
  }
  ```

  *SwiftUI*

  ```swift theme={null}
  import SwiftUI
  import AppstackSDK

  @main
  struct MyApp: App {
      init() {
          AppstackAttributionSdk.shared.configure(
              apiKey: "your_api_key",
              isDebug: false,
              endpointBaseUrl: nil,
              logLevel: .info
          )
      }

      var body: some Scene {
          WindowGroup {
              ContentView()
          }
      }
  }
  ```

  **Configuration parameters**

  ```swift theme={null}
  // Production configuration
  AppstackAttributionSdk.shared.configure(
      apiKey: "your_api_key",
      isDebug: false,  // Uses production URL
      endpointBaseUrl: nil,
      logLevel: .info
  )
  ```

  **Sending events**

  ```swift theme={null}
  // Standard events using EventType enum
  AppstackAttributionSdk.shared.sendEvent(event: .LOGIN)
  AppstackAttributionSdk.shared.sendEvent(
      event: .PURCHASE,
      parameters: ["revenue": 29.99, "currency": "USD"]
  )
  AppstackAttributionSdk.shared.sendEvent(
      event: .SUBSCRIBE,
      parameters: ["revenue": 9.99, "currency": "USD"]
  )

  // Custom events
  AppstackAttributionSdk.shared.sendEvent(
      event: .CUSTOM,
      name: "user_attributes",
      parameters: [
          "email": "test@example.com",
          "name": "first_name last_name",
          "phone_number": "+33060000000",
          "date_of_birth": "2026-02-01"
      ]
  )
  ```

  **EventType values (use standard when possible):**

  * Auth/account: `LOGIN`, `SIGN_UP`, `REGISTER`
  * Monetization: `PURCHASE`, `ADD_TO_CART`, `ADD_TO_WISHLIST`, `INITIATE_CHECKOUT`, `START_TRIAL`, `SUBSCRIBE`
  * Games: `LEVEL_START`, `LEVEL_COMPLETE`
  * Engagement: `TUTORIAL_COMPLETE`, `SEARCH`, `VIEW_ITEM`, `VIEW_CONTENT`, `SHARE`
  * Catch-all: `CUSTOM`

  **Enhanced app campaigns**

  * For revenue events, send:
    * `revenue` or `price` (number)
    * `currency` (e.g. `EUR`, `USD`)
  * To improve Meta matching, include when possible:
    * `email`
    * `name` (first + last name)
    * `phone_number` (also accepted as `phone` or `phoneNumber`)
    * `date_of_birth` (`YYYY-MM-DD`; also accepted as `birthdate`, `birthday`, or `dateOfBirth`)
    * `gender`
  * Appstack automatically encrypts these matching parameters before using them for attribution matching.
</Prompt>

## **Repository**

Here, you will find the [GitHub iOS Appstack SDK documentation](https://github.com/appstack-tech/ios-appstack-sdk). Please use the latest available version of the SDK.

## **Quickstart**

Use this path when you only need the minimum production integration:

1. Add the Swift package from `https://github.com/appstack-tech/ios-appstack-sdk.git`.
2. Copy the **Production** API key from **SDK** in Appstack.
3. Call `AppstackAttributionSdk.shared.configure(...)` during app startup.
4. Send standard events such as `.LOGIN`, `.SIGN_UP`, `.PURCHASE`, and `.SUBSCRIBE`.
5. Confirm events appear in the Appstack SDK page before enabling downstream integrations.

```swift theme={null}
import AppstackSDK

AppstackAttributionSdk.shared.configure(
    apiKey: "your_production_api_key",
    isDebug: false,
    endpointBaseUrl: nil,
    logLevel: .info
)

AppstackAttributionSdk.shared.sendEvent(
    event: .PURCHASE,
    parameters: ["revenue": 29.99, "currency": "USD"]
)
```

## **Requirements**

1. iOS 13.0+
2. Xcode 14.0+
3. Swift 5.0+

## **Initial setup**

<Steps>
  <Step title="Installation" stepNumber={1}>
    You can install the SDK via **Swift Package Manager (SPM)** by adding the following dependency to your `Package.swift` file:

    ```swift theme={null}
    dependencies: [
        // Set `from:` to the latest stable semver from the repo’s releases (do not leave a stale pin).
        .package(url: "https://github.com/appstack-tech/ios-appstack-sdk.git", from: "X.Y.Z")
    ]
    ```

    Or directly from Xcode:

    1. Go to **File > Add Packages**.
    2. Enter the repository URL: `https://github.com/appstack-tech/ios-appstack-sdk.git`.
    3. Select the desired version and click **Add Package**.
  </Step>

  <Step title="Initialization" stepNumber={2}>
    Follow these steps to get the API key:

    1. In Appstack, from the side menu, select **SDK** and ensure you are selecting the correct application.
    2. Select the **Production** environment.
    3. Copy the **API key**.

    *AppDelegate*

    ```swift theme={null}
    import UIKit
    import AppTrackingTransparency
    import AppstackSDK

    @main
    class AppDelegate: UIResponder, UIApplicationDelegate {
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            // Configure Appstack SDK
            AppstackAttributionSdk.shared.configure(
                apiKey: "your_api_key",
                isDebug: false,
                endpointBaseUrl: nil,
                logLevel: .info
            )

            // Request tracking permission and enable Apple Ads Attribution
            if #available(iOS 14.3, *) {
                ATTrackingManager.requestTrackingAuthorization { status in
                    AppstackASAAttribution.shared.enableAppleAdsAttribution()
                }
            }

            return true
        }
    }
    ```

    *SwiftUI*

    ```swift theme={null}
    import SwiftUI
    import AppstackSDK

    @main
    struct MyApp: App {
        init() {
            AppstackAttributionSdk.shared.configure(
                apiKey: "your_api_key",
                isDebug: false,
                endpointBaseUrl: nil,
                logLevel: .info
            )
        }

        var body: some Scene {
            WindowGroup {
                ContentView()
            }
        }
    }
    ```
  </Step>

  <Step title="Configuration parameters" stepNumber={3}>
    The AppstackAttributionSdk.shared.configure() method supports the following parameters:

    1. `apiKey` (String, required): Your Appstack API key.
    2. `isDebug` (Bool, default: false): Leave as 'false' for production. See [Development setup](#development-setup) if you need to test against the development environment.
    3. `logLevel` (LogLevel, default: .info): Logging level for debugging.

    **Configuration examples**

    ```swift theme={null}
    // Production configuration
    AppstackAttributionSdk.shared.configure(
        apiKey: "your_api_key",
        isDebug: false,  // Uses production URL
        endpointBaseUrl: nil,
        logLevel: .info
    )
    ```
  </Step>

  <Step title="Sending events">
    <Note>
      **Important notes**

      1. Initialize the SDK during app startup before sending events
      2. Event names must match those defined in the Appstack platform
      3. Parameters are passed as a dictionary \[String: Any] and can include any key-value pairs (e.g., revenue, currency, quantity)
      4. Revenue parameters support automatic type conversion (Double, Int, Float, String)
      5. Revenue ranges are configured in the Appstack platform and automatically synchronized
    </Note>

    **Predefined event values**

    The SDK provides better type safety with predefined event types:

    ```swift theme={null}
    // Standard events using EventType enum
    AppstackAttributionSdk.shared.sendEvent(event: .LOGIN)
    AppstackAttributionSdk.shared.sendEvent(
        event: .PURCHASE,
        parameters: ["revenue": 29.99, "currency": "USD"]
    )
    AppstackAttributionSdk.shared.sendEvent(
        event: .SUBSCRIBE,
        parameters: ["revenue": 9.99, "currency": "USD"]
    )

    // Custom events
    AppstackAttributionSdk.shared.sendEvent(
        event: .CUSTOM,
        name: "user_attributes",
        parameters: [
            "email": "test@example.com",
            "name": "first_name last_name",
            "phone_number": "+33060000000",
            "date_of_birth": "2026-02-01"
        ]
    )
    ```

    **Available EventType values**

    It is recommended to use standard events for a smoother experience.

    <Note>
      The `INSTALL` event is tracked automatically on SDK initialization. Do not send it manually.
    </Note>

    ```swift theme={null}
    public enum EventType: String {
    // Authentication & account
    case LOGIN
    case SIGN_UP
    case REGISTER

    // Monetization
    case PURCHASE
    case ADD_TO_CART
    case ADD_TO_WISHLIST
    case INITIATE_CHECKOUT
    case START_TRIAL
    case SUBSCRIBE

    // Games / progression
    case LEVEL_START
    case LEVEL_COMPLETE

    // Engagement
    case TUTORIAL_COMPLETE
    case SEARCH
    case VIEW_ITEM
    case VIEW_CONTENT
    case SHARE

    // Catch-all
    case CUSTOM  // For custom events
    }
    ```

    **Enhanced app campaigns**

    <Tip>
      When running enhanced app campaigns (EACs), it is highly recommended to send multiple parameters with the in-app event to improve matching quality.
    </Tip>

    For any event that represents revenue, we recommend sending:

    1. `revenue` or `price` (number).
    2. `currency` (string, e.g. `EUR`, `USD`).

    ```swift theme={null}
    AppstackAttributionSdk.shared.sendEvent(
    event: .PURCHASE,
    parameters: ["revenue": 4.99, "currency": "EUR"]
    )
    ```

    To improve matching quality on Meta and TikTok, send events including the following parameters if you can fulfill them. Appstack automatically encrypts these matching parameters before using them for attribution matching.

    1. `email`.
    2. `name` (first + last name in the same field).
    3. `phone_number` — also accepted as `phone` or `phoneNumber`.
    4. `date_of_birth` (recommended format: `YYYY-MM-DD`) — also accepted as `birthdate`, `birthday`, or `dateOfBirth`.
    5. `gender`.
  </Step>
</Steps>

## **Appstack ID and attribution params**

After `configure`, you can read the Appstack user ID and the attribution map for partner integrations (for example Superwall, RevenueCat).

```swift theme={null}
let appstackId = AppstackAttributionSdk.shared.getAppstackId()
let attributionParams = await AppstackAttributionSdk.shared.getAttributionParams()
```

* **`getAppstackId()`** — Appstack user identifier when a partner expects `$appstackId` or similar.
* **`getAttributionParams()`** — Attribution payload (campaign, media source, click IDs, device identifiers where available) to forward to partners.

## **Development setup**

If you want to test the SDK against the Appstack development environment before shipping, follow these extra steps:

1. In Appstack, from the side menu, select **SDK**, switch to the **Development** environment, and copy the **Development API key**. This key is separate from your production key.
2. In your `configure(...)` call, use the development key and set `isDebug: true`:

```swift theme={null}
AppstackAttributionSdk.shared.configure(
    apiKey: "your_development_api_key",
    isDebug: true,
    logLevel: .debug
)
```

The `isDebug` flag must match the key you're using: development key with `isDebug: true`, production key with `isDebug: false`. The flag tells the SDK which environment URL to route to.

## **Security and privacy**

* Never commit API keys to version control.
* Use separate production and development keys, and keep `isDebug` aligned with the selected key.
* Do not put personally identifiable information in event names.
* Only send matching parameters such as `email`, `name`, `phone_number`, and `date_of_birth` when your app has the right consent and compliance basis. Appstack automatically encrypts these fields before using them for attribution matching.
* Prefer standard event types for common flows so event mapping remains consistent across Appstack and ad integrations.

## **Advanced configuration**

### **SDK behavior**

The SDK automatically:

* Fetches configuration from Appstack servers.
* Manages conversion value updates based on event tracking.
* Handles revenue range matching for conversion optimization.
* Processes events in time-based windows (0-2 days, 3-7 days, 8-35 days).
* Queues events when the configuration is not ready.

### **Event processing**

* Events are processed asynchronously to avoid blocking the main thread.
* The SDK queues events if the configuration is not yet loaded.
* Revenue parameters are automatically validated and converted to numeric values.
* Events are matched against configured revenue ranges in real-time.

## **Limitations**

### **Attribution timing**

* Apple Ads attribution requires iOS 14.3+.
* Apple Ads attribution requires app installation from the App Store or TestFlight.
* Attribution data can take 24-48 hours to appear.
* Some attribution behavior may not be available in development or simulator environments.

### **Event tracking**

* The SDK must be initialized during app startup before any tracking calls.
* `INSTALL` is tracked automatically on SDK initialization. Do not send it manually.
* Revenue events should include `revenue` or `price` and `currency`.
* Event processing is asynchronous and can queue events while configuration is loading.

## **Troubleshooting**

### **Configuration fails**

* Confirm the API key was copied from the correct app and environment in Appstack.
* Check that the SDK package is installed from the correct repository URL.

### **Events do not appear**

* Confirm `configure(...)` runs before the first `sendEvent(...)` call.
* Confirm the device has network connectivity.
* Check that revenue events include a numeric `revenue` or `price` value and a valid `currency`.
* Allow a few minutes for events to appear in the dashboard.

### **iOS install event does not appear**

* If you have a StoreKit test configuration enabled and are using a production API key, the SDK will not record the install.
* For StoreKit test configuration runs, use the development API key.
* For production-key validation, disable the StoreKit test configuration.

### **Apple Ads attribution does not appear**

* Confirm the app was installed from the App Store or TestFlight.
* Confirm the device runs iOS 14.3+.
* Call `AppstackASAAttribution.shared.enableAppleAdsAttribution()` after initialization and in the appropriate ATT flow.
* Allow 24-48 hours for attribution data to appear.

## **Superwall**

To start using the Superwall integration, [click here](/Integrations/superwall) to see the correct SDK documentation.

## **Apple Ads**

To start using the Apple Ads integration, [click here](/Integrations/apple-ads) to see the correct SDK documentation.

## **Verification checklist**

* Swift package installed from `https://github.com/appstack-tech/ios-appstack-sdk.git`.
* App target meets iOS 13.0+, Xcode 14.0+, and Swift 5.0+ requirements.
* Production API key is used with `isDebug: false`.
* Development API key is used with `isDebug: true` only in development builds.
* `configure(...)` runs once during app startup.
* `INSTALL` is not sent manually.
* Login, signup, purchase, subscription, and other key app events use standard event types where possible.
* Revenue events include `revenue` or `price` and `currency`.
* Custom events use `.CUSTOM` with a descriptive `name`.
* Appstack ID and attribution params are available before wiring partner integrations.
* Apple Ads attribution is enabled only on supported iOS versions and in the correct permission flow.
* Events are visible in the Appstack SDK page before launch.

## **Support**

For questions or issues:

1. Check the [GitHub Repository](https://github.com/appstack-tech/ios-appstack-sdk).
2. Contact our support team at [support@appstack.tech](mailto:support@appstack.tech).
3. Open an issue in the repository.

<Prompt description="Use Cursor, Claude Code, or another AI to validate your existing Appstack Swift SDK integration." actions={["copy", "cursor"]}>
  You are an expert iOS engineer reviewing my existing Appstack Swift SDK integration. You are running inside an IDE assistant such as Cursor or Claude Code and you can see my codebase.

  Your goal is to **validate that my integration fully matches the official Swift SDK documentation** and identify any missing or incorrect steps. When I paste this prompt and share my project files, you should:

  1. **Package & environment**
     * Inspect my SwiftPM / Xcode configuration to confirm:
       * The Appstack SDK package is added with the correct URL (`https://github.com/appstack-tech/ios-appstack-sdk.git`) and a **current** dependency rule (`from:` / version range) matching the latest stable release, not an outdated pinned version.
       * My project meets the requirements (iOS 13.0+, Xcode 14.0+, Swift 5.0+).
     * Point out any version or package setup issues and propose exact fixes.

  2. **SDK initialization (AppDelegate / SwiftUI)**
     * Locate how and where I call:
       * `AppstackAttributionSdk.shared.configure(...)`
       * `AppstackASAAttribution.shared.enableAppleAdsAttribution()` (where applicable)
     * Verify that:
       * Initialization happens in app startup (`application(_:didFinishLaunchingWithOptions:)` or `@main` SwiftUI `init`).
       * Required parameters (`apiKey`) are set, and optional parameters (`isDebug`, `endpointBaseUrl`, `logLevel`) are used appropriately for dev vs prod.
       * For iOS 14.3+, Apple Ads attribution is enabled in the correct permission flow, e.g. inside the ATTrackingManager callback.
     * Suggest precise code changes if initialization is missing, duplicated, or in the wrong place.

  3. **Event tracking implementation**
     * Find all uses of `AppstackAttributionSdk.shared.sendEvent(...)` and verify:
       * Standard `EventType` cases are used for login, signup, purchases, subscriptions, etc.
       * Revenue events (`.PURCHASE`, `.SUBSCRIBE`, etc.) send `revenue` (or `price`) and `currency` in the `parameters` dictionary.
       * Custom events use `.CUSTOM` with a descriptive `name` and, for EAC / Meta optimization, parameters such as `email`, `name`, `phone_number`, and `date_of_birth`, noting that Appstack automatically encrypts these matching parameters before using them for attribution matching.
     * Call out missing or inconsistent events and propose concrete `sendEvent` calls that fit my app flows.

  4. **Advanced behavior & limitations**
     * Validate that my integration respects documented behavior:
       * SDK is initialized during app startup before sending events.
       * I understand that events are queued and processed asynchronously and that revenue ranges and conversion windows are handled by the SDK.
     * Flag any patterns in my code (e.g. blocking calls, repeated reconfiguration) that could conflict with these assumptions.

  5. **Validation report & checklist**
     * Produce a clear report summarizing:
       * What is already correctly implemented and production-ready.
       * What is missing, misconfigured, or risky, with specific files, functions, and suggested code changes.
</Prompt>
