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

# SDK Integration

> Quickly integrate iOS RUM SDK for real-time monitoring of app performance, errors, and user behavior

<Info>
  Flashduty iOS RUM SDK supports **iOS 12.0, iPadOS 12.0, tvOS 12.0** and above. By integrating the SDK, you can monitor your iOS app's performance, errors, and user behavior in real-time.
</Info>

<Note>
  **About Dependencies and Package Names**

  Flashduty iOS SDK is fully compatible with the Datadog open-source protocol. When adding dependencies via Swift Package Manager or CocoaPods, use names like `FlashcatCore`, `FlashcatRUM`, and `FlashcatTrace`, but in code, import modules like `DatadogCore`, `DatadogRUM`, and `DatadogTrace`. You can seamlessly leverage Datadog ecosystem documentation, examples, and best practices while enjoying Flashduty platform services.
</Note>

## Integration Steps

<Steps>
  <Step title="Add SDK Dependencies">
    Flashduty iOS SDK supports Swift Package Manager and CocoaPods:

    <Tabs>
      <Tab title="Swift Package Manager">
        1. In Xcode, open your project and select **File > Add Package Dependencies**

        2. Enter the Flashduty SDK Git repository URL:
           ```
           https://github.com/flashcatcloud/fc-sdk-ios
           ```

        3. Select version rule:
           * **Recommended**: Select **Up to Next Major Version** and enter the latest version number (e.g., `0.3.0`)
           * This allows bug fixes and minor updates while maintaining compatibility

        4. Click **Add Package** and wait for Xcode to download dependencies

        5. In the **Choose Package Products** window, select modules to add to your Target:
           * `FlashcatCore` - Core SDK (required)
           * `FlashcatRUM` - RUM feature module (required)
           * `FlashcatTrace` - Trace feature module (required when enabling the Trace feature, automatic Trace spans, or manual spans)
           * `FlashcatWebViewTracking` - WebView tracking (optional)
           * `FlashcatCrashReporting` - Crash reporting (recommended)

        6. Ensure each module is linked to the correct Target, click **Add Package** to complete
      </Tab>

      <Tab title="CocoaPods">
        Add the following dependencies to your `Podfile`:

        ```ruby Podfile theme={null}
        pod 'FlashcatCore', '~> 0.3.0'    # Core SDK (required)
        pod 'FlashcatRUM', '~> 0.3.0'     # RUM feature (required)
        pod 'FlashcatTrace', '~> 0.3.0'   # Trace feature (required for Trace feature or manual spans)

        # Optional modules
        pod 'FlashcatWebViewTracking', '~> 0.3.0'   # WebView tracking
        pod 'FlashcatCrashReporting', '~> 0.3.0'    # Crash reporting
        ```

        Then run `pod install` and open your project using the `.xcworkspace` file.
      </Tab>
    </Tabs>

    <Tip>
      **Get Latest Version**

      Check the [SDK Release Page](https://github.com/flashcatcloud/fc-sdk-ios/releases) for the latest stable version. Pin to a specific version to avoid unexpected updates.
    </Tip>
  </Step>

  <Step title="Get Application Credentials">
    In the Flashduty console's **RUM Application Management** page:

    1. Create or select an iOS application
    2. Get the following credentials:
       * **Application ID** - Application unique identifier
       * **Client Token** - Client access token
  </Step>

  <Step title="Initialize SDK">
    Initialize the SDK in your `AppDelegate.swift`'s `application(_:didFinishLaunchingWithOptions:)` method:

    ```swift AppDelegate.swift theme={null}
    import UIKit
    import DatadogCore

    @main
    class AppDelegate: UIResponder, UIApplicationDelegate {
        func application(
            _ application: UIApplication,
            didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
        ) -> Bool {
            Datadog.initialize(
                with: Datadog.Configuration(
                    clientToken: "<CLIENT_TOKEN>",
                    env: "<ENV_NAME>"
                ),
                trackingConsent: .granted
            )

            return true
        }
    }
    ```

    <Note>
      **Parameter Description:**

      * `clientToken` - Client token obtained from console (required)
      * `env` - Environment name, e.g., `production`, `staging` (required)
      * `trackingConsent` - User tracking consent state (see below)
    </Note>

    **TrackingConsent States:**

    | State         | Behavior                                                                  |
    | ------------- | ------------------------------------------------------------------------- |
    | `.granted`    | Start collecting data and send to Flashduty                               |
    | `.pending`    | Start collecting and batching data, but don't send, wait for confirmation |
    | `.notGranted` | Do not collect any data                                                   |

    <Tip>
      You can dynamically modify tracking consent state after initialization via `Datadog.set(trackingConsent:)`.
    </Tip>
  </Step>

  <Step title="Enable RUM Features">
    Configure and enable RUM features. Recommend enabling early in `AppDelegate`:

    ```swift AppDelegate.swift theme={null}
    import DatadogRUM

    RUM.enable(
        with: RUM.Configuration(
            applicationID: "<RUM_APPLICATION_ID>",
            uiKitViewsPredicate: DefaultUIKitRUMViewsPredicate(),
            uiKitActionsPredicate: DefaultUIKitRUMActionsPredicate(),
            swiftUIViewsPredicate: DefaultSwiftUIRUMViewsPredicate(),
            swiftUIActionsPredicate: DefaultSwiftUIRUMActionsPredicate(
                isLegacyDetectionEnabled: true
            ),
            urlSessionTracking: RUM.Configuration.URLSessionTracking()
        )
    )
    ```

    <Note>
      **Configuration Parameter Description:**

      * `applicationID` - RUM application ID obtained from console
      * `uiKitViewsPredicate` - UIKit view tracking strategy
      * `uiKitActionsPredicate` - UIKit user action tracking strategy
      * `swiftUIViewsPredicate` - SwiftUI view tracking strategy
      * `swiftUIActionsPredicate` - SwiftUI user action tracking strategy
      * `urlSessionTracking` - URLSession network request tracking configuration
    </Note>

    <Check>
      The SDK will automatically start collecting the following data:

      * UIKit and SwiftUI view tracking
      * User interaction events
      * Network request monitoring
    </Check>
  </Step>

  <Step title="Configure Network Tracking (Optional)">
    **Configure first-party hosts and trace correlation:**

    To correlate mobile RUM Resources with backend traces, configure `firstPartyHostsTracing` in `RUM.Configuration` for your first-party hosts. Hosts must be host names only, without `http://`, `https://`, or path. If you already called `RUM.enable(...)` in the previous step, merge the `urlSessionTracking` setting below into that same `RUM.Configuration`; do not enable RUM twice.

    ```swift AppDelegate.swift theme={null}
    import DatadogRUM

    RUM.enable(
        with: RUM.Configuration(
            applicationID: "<RUM_APPLICATION_ID>",
            uiKitViewsPredicate: DefaultUIKitRUMViewsPredicate(),
            urlSessionTracking: RUM.Configuration.URLSessionTracking(
                firstPartyHostsTracing: .traceWithHeaders(
                    hostsWithHeaders: [
                        "example.com": [.datadog, .tracecontext],
                        "api.example.com": [.datadog, .tracecontext]
                    ],
                    sampleRate: 100
                )
            )
        )
    )
    ```

    <Note>
      Configuring `example.com` also matches subdomains such as `api.example.com`. `sampleRate` must be between `0` and `100`; lower it in production according to your sampling policy.
    </Note>

    **Enable Trace:**

    If you need Trace span collection or manual span APIs, enable Trace after `Datadog.initialize(...)`:

    ```swift AppDelegate.swift theme={null}
    import DatadogTrace

    Trace.enable()
    ```

    To let the Trace feature automatically create spans for first-party `URLSession` requests, configure the same first-party hosts in `Trace.Configuration` and use the following call instead of the plain `Trace.enable()` above:

    ```swift AppDelegate.swift theme={null}
    import DatadogTrace

    Trace.enable(
        with: Trace.Configuration(
            urlSessionTracking: Trace.Configuration.URLSessionTracking(
                firstPartyHostsTracing: .traceWithHeaders(
                    hostsWithHeaders: [
                        "example.com": [.datadog, .tracecontext],
                        "api.example.com": [.datadog, .tracecontext]
                    ],
                    sampleRate: 100
                )
            )
        )
    )
    ```

    **Enable URLSession Tracking:**

    To monitor network requests sent from `URLSession` instances, enable `URLSessionInstrumentation` and pass your delegate class type:

    ```swift theme={null}
    import DatadogRUM

    URLSessionInstrumentation.enable(
        with: .init(
            delegateClass: YourSessionDelegate.self
        )
    )

    let session = URLSession(
        configuration: .default,
        delegate: YourSessionDelegate(),
        delegateQueue: nil
    )
    ```

    <Check>
      **Auto-tracked Network Information:**

      * Request URL, method, status code
      * Request and response headers
      * Request duration and data size
      * Network error information
      * Trace headers injected for sampled first-party requests, such as `x-datadog-*`, `traceparent`, and `tracestate`
    </Check>

    <Note>
      Only network requests initiated while a view is active are recorded as RUM Resources. Backend services must receive and propagate these trace headers to complete frontend-backend trace correlation.
    </Note>
  </Step>
</Steps>

## View Tracking

Flashduty iOS SDK supports automatic tracking of UIKit and SwiftUI views.

### UIKit View Auto Tracking

<Note>
  UIKit views are automatically tracked via `DefaultUIKitRUMViewsPredicate`. The SDK tracks `UIViewController` lifecycle, automatically recording view display and hide events.
</Note>

### SwiftUI View Tracking

For SwiftUI apps, add the `.trackRUMView()` modifier to views:

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

struct ProductView: View {
    var body: some View {
        VStack {
            Text("Product Details")
            // Your view content
        }
        .trackRUMView(name: "Product")
    }
}
```

<Tip>
  The `trackRUMView(name:)` method automatically starts and stops view tracking when SwiftUI views appear and disappear.
</Tip>

### Custom View Tracking

For more granular control, manually track views:

```swift theme={null}
import DatadogRUM

// Start tracking view
RUMMonitor.shared().startView(
    key: "view-key",
    name: "View Name",
    attributes: [:]
)

// Stop tracking view
RUMMonitor.shared().stopView(
    key: "view-key",
    attributes: [:]
)
```

## User Action Tracking

### UIKit Action Auto Tracking

<Check>
  User actions in UIKit (like button taps, switch toggles, etc.) are automatically tracked via `DefaultUIKitRUMActionsPredicate`.
</Check>

### SwiftUI Action Tracking

For SwiftUI controls, add the `.trackRUMTapAction()` modifier:

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

struct CheckoutView: View {
    var body: some View {
        Button("Complete Purchase") {
            // Button action
        }
        .trackRUMTapAction(name: "Purchase")
    }
}
```

<Warning>
  Using `.trackRUMTapAction(name:)` inside `List` may affect default gestures (e.g., disabling `Button` actions or breaking `NavigationLink`). For `List` elements, recommend using custom action API.
</Warning>

### Custom Action Tracking

Manually track user actions:

```swift theme={null}
import DatadogRUM

RUMMonitor.shared().addAction(
    type: .tap,
    name: "Button Tapped",
    attributes: ["button_id": "submit"]
)
```

## Advanced Configuration

### Track Errors

Flashduty iOS SDK automatically captures app crashes and uncaught exceptions. You can also manually record errors:

```swift theme={null}
import DatadogRUM

RUMMonitor.shared().addError(
    message: "Network request failed",
    type: "NetworkError",
    source: .network,
    attributes: [
        "url": "https://api.example.com",
        "status_code": 500
    ]
)
```

<Check>
  All error information is displayed in the console's RUM Explorer, including error stack, attributes, and JSON details.
</Check>

<Note>
  For detailed error reporting configuration, see [iOS Error Reporting](/en/rum/error-tracking/erro-reporting/ios).
</Note>

### Track Background Events

You can track events when the app is running in the background (e.g., crashes and network requests):

```swift theme={null}
RUM.enable(
    with: RUM.Configuration(
        applicationID: "<RUM_APPLICATION_ID>",
        trackBackgroundEvents: true
    )
)
```

<Warning>
  Tracking background events may generate additional sessions, affecting billing. If you have questions, please contact Flashduty support team.
</Warning>

### Track User Information

You can set user information for the current session to track specific user behavior:

```swift theme={null}
import DatadogCore

Datadog.setUserInfo(
    id: "user-123",
    name: "John Doe",
    email: "john.doe@example.com"
)
```

<Warning>
  Only standard user fields are supported: `id`, `name`, `email`, and `anonymous_id`. Other user attributes are not supported. If needed, configure them under `context`.
</Warning>

### Offline Data Handling

The iOS SDK ensures data availability when the user's device is offline:

<Check>
  **Data Persistence Mechanism:**

  * Events are stored locally in batches when network signal is weak or device battery is low
  * Automatically uploaded when network recovers, ensuring no data loss
  * Old data is automatically cleaned up to avoid excessive disk usage
</Check>

<Note>
  Even if users use the app while offline, data is retained and uploaded when network recovers, ensuring no monitoring data is lost.
</Note>

## WebView Integration

If your iOS app contains WKWebView, you can enable WebView tracking to monitor web content performance and errors.

<Steps>
  <Step title="Add WebView Dependency">
    When adding package dependencies in Swift Package Manager, also add the `FlashcatWebViewTracking` module.
  </Step>

  <Step title="Enable WebView Tracking">
    Enable WebView tracking in your ViewController:

    ```swift theme={null}
    import DatadogWebViewTracking
    import WebKit

    let webView = WKWebView()

    // Enable tracking for specified WKWebView
    WebViewTracking.enable(
        webView: webView,
        hosts: ["example.com", "*.example.com"]
    )
    ```

    <Note>
      **Parameter Description:**

      * `webView` - WKWebView instance to track
      * `hosts` - List of domains to track, supports wildcards (e.g., `*.example.com`)
    </Note>
  </Step>
</Steps>

<Check>
  Web pages in WebView can now be correlated with native app RUM data.
</Check>

### Disable Auto User Data Collection

To comply with privacy regulations or organizational data governance policies, you can disable automatic user data collection.

<Steps>
  <Step title="Go to Application Management">
    After creating an application, go to the **Application Management** page and click your application.
  </Step>

  <Step title="Configure Data Collection">
    Click the **User Data Collection** option and use toggles to control the following settings:

    * Client IP collection
    * Geo-location data collection
  </Step>
</Steps>

## Verify Integration

After integration, verify that the integration is successful:

<Steps>
  <Step title="Check Console Logs">
    Search for `Datadog` keyword in Xcode console to view SDK initialization and data reporting logs.
  </Step>

  <Step title="Access Console">
    Log in to Flashduty console, go to the corresponding RUM application, and check if data is being reported.
  </Step>

  <Step title="Trigger Test Events">
    Perform the following actions in the app to verify data collection:

    * Open different pages in the app to verify page view events
    * Perform user actions (taps, swipes, etc.) to verify interaction events
    * Trigger network requests to verify resource loading events
    * Manually trigger an error to verify error tracking

    <Check>
      If you see data reporting and data appears in the console, the integration is successful!
    </Check>
  </Step>
</Steps>

## Next Steps

<CardGroup cols={2}>
  <Card title="Advanced Configuration" icon="sliders" href="/en/rum/sdk/ios/advanced-config">
    Configure advanced SDK features like custom sampling, user identification, global context, etc.
  </Card>

  <Card title="Data Collection" icon="database" href="/en/rum/sdk/ios/data-collection">
    Learn about data types and data structures collected by the SDK
  </Card>

  <Card title="Insights" icon="chart-line" href="/en/rum/analytics/native">
    View and analyze app performance, errors, and user behavior data
  </Card>

  <Card title="Error Tracking" icon="bug" href="/en/rum/error-tracking/overview">
    Configure crash reporting and error tracking features
  </Card>
</CardGroup>
