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

# iOS (Swift)

> Add DATALYR tracking to your iOS app with the Swift SDK

Add DATALYR to your iOS app to track users, conversions, and revenue with server-side attribution and SKAdNetwork support.

## Use Cases

**E-commerce Apps**
Track purchases, cart additions, and product views. Attribute revenue back to ad campaigns on Meta, Google, and TikTok.

**Subscription Apps**
Monitor trial starts, conversions, and renewals with iOS 14+ attribution via SKAdNetwork.

**SaaS Mobile Apps**
Track feature usage, user engagement, and subscription upgrades with cross-device attribution.

**Mobile Games**
Track in-app purchases, level completions, and retention with gaming-optimized SKAdNetwork templates.

## Before You Start

* [ ] You have a DATALYR account
* [ ] You've created a workspace
* [ ] You have an iOS app project in Xcode
* [ ] iOS 13.0+ deployment target
* [ ] Swift 5.0+

## Step 1: Get Your API Key

1. Log in to your DATALYR dashboard
2. Go to **Settings → API Keys**
3. Create a new API key or copy an existing one
4. Your API key will start with `dk_`

## Step 2: Install the SDK

### Option 1: Swift Package Manager (Recommended)

1. In Xcode, select **File → Add Package Dependencies**
2. Enter the repository URL:
   ```
   https://github.com/datalyr/swift
   ```
3. Select version **2.1.3** or later
4. Add **DatalyrSDK** to your app target

### Option 2: CocoaPods

Add to your `Podfile`:

```ruby theme={null}
pod 'DatalyrSwift', '~> 2.1.3'
```

Then run:

```bash theme={null}
pod install
```

### Option 3: Manual Installation

1. Download the SDK from [GitHub Releases](https://github.com/datalyr/swift/releases)
2. Drag `Sources/DatalyrSDK` folder into your Xcode project
3. Ensure "Copy items if needed" is checked

## Step 3: Initialize the SDK

### SwiftUI App

Add to your App struct:

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

@main
struct MyApp: App {
    init() {
        Task {
            let config = DatalyrConfig(
                apiKey: "dk_your_api_key", // Replace with your API key
                debug: true // Enable debug logs in development
            )

            do {
                try await DatalyrSDK.shared.initialize(config: config)
                print("DATALYR initialized successfully")
            } catch {
                print("DATALYR initialization failed: \(error)")
            }
        }
    }

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

### UIKit App

Add to your AppDelegate:

```swift theme={null}
import UIKit
import DatalyrSDK

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        Task {
            let config = DatalyrConfig(
                apiKey: "dk_your_api_key",
                debug: true
            )

            try? await DatalyrSDK.shared.initialize(config: config)
        }

        return true
    }
}
```

## Step 4: Track Your First Event

Test that tracking works:

```swift theme={null}
import DatalyrSDK

// Track a custom event
await DatalyrSDK.shared.track("App Opened", eventData: [
    "screen": "Home",
    "version": "1.0.0"
])
```

## Step 5: Verify Tracking

1. Run your app in the simulator or on a device
2. Go to your DATALYR dashboard
3. Click **Events** in the sidebar
4. You should see an `app_opened` event within 10 seconds

If you see events, you're done!

## What Gets Tracked Automatically

When `enableAutoEvents` is enabled (default: true):

* `app_install` - First app open
* `app_open` - App launches
* `app_background` - App enters background
* `app_foreground` - App returns to foreground
* `app_update` - App version changes
* `session_start` - New session begins
* `session_end` - Session expires

## Track Custom Events

Track any custom event with optional properties:

```swift theme={null}
// Simple event
await DatalyrSDK.shared.track("Button Clicked")

// Event with properties
await DatalyrSDK.shared.track("Product Viewed", eventData: [
    "product_id": "SKU123",
    "product_name": "Premium Subscription",
    "price": 49.99,
    "currency": "USD",
    "category": "Subscriptions"
])
```

## Track Purchases

Track purchase events with revenue:

```swift theme={null}
// Simple purchase (automatically updates SKAdNetwork conversion value)
await DatalyrSDK.shared.trackPurchase(
    value: 99.99,
    currency: "USD",
    productId: "premium_subscription"
)

// Detailed purchase event
await DatalyrSDK.shared.track("Purchase Completed", eventData: [
    "order_id": "ORDER123",
    "amount": 149.99,
    "currency": "USD",
    "products": [
        ["id": "SKU1", "name": "Product 1", "price": 99.99],
        ["id": "SKU2", "name": "Product 2", "price": 50.00]
    ],
    "tax": 12.50,
    "shipping": 5.00
])
```

## Track Subscriptions

Track subscription events for IAP subscriptions:

```swift theme={null}
await DatalyrSDK.shared.trackSubscription(
    value: 9.99,
    currency: "USD",
    plan: "monthly_pro"
)
```

## Identify Users

Identify users after signup or login for cross-device attribution:

```swift theme={null}
await DatalyrSDK.shared.identify("user_123", properties: [
    "email": "user@example.com",
    "name": "John Doe",
    "plan": "premium",
    "created_at": "2025-09-29"
])
```

## Track Screen Views

Track screen or view controller views:

```swift theme={null}
// SwiftUI
.onAppear {
    Task {
        await DatalyrSDK.shared.screen("Product Details", properties: [
            "product_id": "SKU123",
            "category": "Electronics"
        ])
    }
}

// UIKit
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    Task {
        await DatalyrSDK.shared.screen("Product Details", properties: [
            "product_id": "SKU123"
        ])
    }
}
```

## SKAdNetwork Support (iOS 14+)

Enable SKAdNetwork conversion value tracking:

```swift theme={null}
let config = DatalyrConfig(
    apiKey: "dk_your_api_key",
    skadTemplate: "ecommerce" // or "gaming", "subscription"
)

try await DatalyrSDK.shared.initialize(config: config)

// Events automatically update conversion values
await DatalyrSDK.shared.trackPurchase(value: 99.99, currency: "USD")

// Check conversion value (for testing)
let value = DatalyrSDK.shared.getConversionValue(
    for: "purchase",
    properties: ["revenue": 75.00]
)
print("Conversion value: \(value ?? 0)") // 0-63
```

### SKAdNetwork Templates

Choose a template based on your business model:

* **ecommerce**: Purchase events, revenue ranges
* **gaming**: Level completion, in-app purchases, retention
* **subscription**: Trial starts, conversions, renewals

## Identity Resolution

The SDK includes persistent anonymous IDs for complete user journey tracking:

```swift theme={null}
// Get anonymous ID (persists across app sessions)
let anonymousId = DatalyrSDK.shared.getAnonymousId()

// Pass to your backend for attribution preservation
var request = URLRequest(url: URL(string: "https://api.example.com/purchase")!)
request.httpBody = try? JSONSerialization.data(withJSONObject: [
    "items": cartItems,
    "anonymous_id": anonymousId  // Links server events to mobile events
])

// Identity is automatically linked when you identify a user
await DatalyrSDK.shared.identify("user_123", properties: [
    "email": "user@example.com"
])
```

This creates a link between your mobile app events and server-side events, preserving attribution from ad click to purchase.

## Attribution Tracking

The SDK automatically tracks:

* Deep links and Universal Links
* UTM parameters
* Platform click IDs (fbclid, gclid, ttclid)
* Install referrer
* Campaign data

Get attribution data:

```swift theme={null}
let attribution = DatalyrSDK.shared.getAttributionData()
print(attribution.campaign)
print(attribution.source)
print(attribution.medium)
```

## Session Management

Sessions are automatically tracked with a 30-minute timeout:

```swift theme={null}
// Get current session
let session = DatalyrSDK.shared.getCurrentSession()

// Manually end session
await DatalyrSDK.shared.endSession()

// Reset user (logout)
await DatalyrSDK.shared.reset()
```

## Deep Link Handling

Track deep link opens:

```swift theme={null}
// SwiftUI
.onOpenURL { url in
    Task {
        await DatalyrSDK.shared.track("Deep Link Opened", eventData: [
            "url": url.absoluteString,
            "scheme": url.scheme ?? "",
            "host": url.host ?? ""
        ])
    }
}

// UIKit
func application(
    _ app: UIApplication,
    open url: URL,
    options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
    Task {
        await DatalyrSDK.shared.track("Deep Link Opened", eventData: [
            "url": url.absoluteString
        ])
    }
    return true
}
```

## Offline Support

Events are automatically queued when offline and sent when connection is restored:

```swift theme={null}
// Manually flush queue
await DatalyrSDK.shared.flush()

// Check queue status
let status = DatalyrSDK.shared.getStatus()
print("Queue size: \(status.queueStats.queueSize)")
print("Is online: \(status.queueStats.isOnline)")
```

## Debug Mode

Enable debug logging during development:

```swift theme={null}
let config = DatalyrConfig(
    apiKey: "dk_your_api_key",
    debug: true // Enable console logs
)
```

Debug output includes:

* Event tracking logs
* Network requests
* Queue operations
* Attribution updates
* Error messages

## Privacy & Compliance

### App Tracking Transparency (iOS 14.5+)

Request tracking permission:

```swift theme={null}
import AppTrackingTransparency

ATTrackingManager.requestTrackingAuthorization { status in
    Task {
        await DatalyrSDK.shared.track("ATT Status", eventData: [
            "status": status.rawValue
        ])
    }
}
```

### User Consent

Handle user consent for tracking:

```swift theme={null}
// Track consent
await DatalyrSDK.shared.track("Consent Updated", eventData: [
    "tracking_allowed": false,
    "gdpr_consent": false
])

// Disable tracking
await DatalyrSDK.shared.reset()
```

## Configuration Options

```swift theme={null}
let config = DatalyrConfig(
    apiKey: "dk_your_api_key",        // Required
    debug: false,                      // Enable logging
    enableAutoEvents: true,            // Track lifecycle events
    enableAttribution: true,           // Track attribution data
    skadTemplate: "ecommerce",         // SKAdNetwork template
    maxRetries: 3,                     // Retry failed requests
    retryDelay: 1.0,                   // Seconds between retries
    timeout: 15.0,                     // Request timeout
    batchSize: 10,                     // Events per batch
    flushInterval: 10.0,               // Seconds between flushes
    maxQueueSize: 100                  // Max queued events
)
```

## Troubleshooting

**Events not appearing?**

1. Check API key is correct (starts with `dk_`)
2. Enable debug mode to see logs
3. Verify network connectivity
4. Check `getStatus()` for queue info
5. Call `flush()` to force send events

**Build errors?**

```bash theme={null}
# Clean build folder
cmd+shift+k in Xcode

# Reset package caches
File → Packages → Reset Package Caches

# Update packages
File → Packages → Update to Latest Package Versions
```

**Authentication errors?**

* Get API key from: [https://datalyr.com/settings/api-keys](https://datalyr.com/settings/api-keys)
* Ensure key is active
* Check key permissions

**SKAdNetwork not working?**

Ensure you've added SKAdNetwork IDs to your Info.plist. Contact support for the list of network IDs to add.

## Next Steps

<CardGroup cols={2}>
  <Card title="Verify Tracking" icon="check" href="/getting-started/installation/verify-tracking">
    Confirm events are coming through
  </Card>

  <Card title="Track Custom Events" icon="code" href="/sdks/mobile/ios-sdk">
    Learn the full event tracking API
  </Card>

  <Card title="Connect Integrations" icon="plug" href="/integrations/overview">
    Link Meta, Google, TikTok Ads
  </Card>

  <Card title="View Dashboard" icon="chart-line" href="/features/dashboard">
    See your tracking data
  </Card>
</CardGroup>

## Need Help?

Having issues with iOS tracking? Check our [troubleshooting guide](/troubleshooting/tracking-not-working) or contact support.
