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

# iOS SDK

> Integrate the Kameleoon iOS SDK to run experiments and activate feature flags in native Swift iOS applications.

With the Kameleoon iOS (Swift) SDK, experiments can run and feature flags can activate on native mobile iOS applications. Integrating the SDK into Swift apps is easy, and the footprint (memory and network usage) is low.

**Getting started**: For help getting started, see the [developer guide](#developer-guide).

**Changelog**: Latest version of the Swift SDK: 4.27.1 [Changelog](https://github.com/Kameleoon/client-swift/blob/master/CHANGELOG.md).

**SDK methods**: For the full reference documentation of the iOS SDK methods, see the [reference](#reference) section.

## Developer guide

Follow these steps to install and configure the Kameleoon iOS SDK in your application for the first time.

### Getting started

#### Starter kit

To help with getting started, Kameleoon provides a starter kit and demo application to test the SDK. The starter kit includes a fully configured app with examples demonstrating how SDK methods can be used in an app. The starter kit, demo application, and detailed instructions are available at [Starter kit for iOS](https://github.com/Kameleoon/ios-examples)

#### Prerequisites

* Use Swift version 5.0 or higher on the iOS platform. Support for earlier iOS applications (including earlier Swift versions and Objective-C apps) is not planned. A Universal Framework version is available, compatible both with x86\_64 (for the iOS Simulator) and ARM (for production deployment into the App Store).

#### Installation

You can install the iOS SDK using CocoaPods or Swift Package Manager:

<Tabs defaultTabIndex={1}>
  <Tab title="CocoaPods">
    With <a href="https://guides.cocoapods.org/using/using-cocoapods.html">CocoaPods</a>, paste the following code in your Podfile and replace `YOUR_TARGET_NAME` with the value for your app:

    ```swift theme={null}
    # Podfile
    use_frameworks!

    target 'YOUR_TARGET_NAME' do
      pod 'kameleoonClient'
    end
    ```

    Then, in a command prompt, in the `Podfile` directory, run the install command:

    ```custom_code theme={null}
    pod install
    ```
  </Tab>

  <Tab title="Swift Package Manager">
    With <a href="https://github.com/apple/swift-package-manager">Swift Package Manager</a>, add a <a href="https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app">package dependency to your Xcode project</a>. Select **File > Swift Packages > Add Package Dependency** and enter the repository URL: `https://github.com/Kameleoon/client-swift`.

    Alternatively, you can modify your `Package.swift` file directly:

    ```swift theme={null}
    dependencies: [
      .package(url: "https://github.com/Kameleoon/client-swift.git", from("3.0.3"))
    ]
    ```
  </Tab>
</Tabs>

***

#### Additional configuration

To customize the SDK's behavior, create a `kameleoon-client-swift.plist` configuration file in the root directory of your Xcode project. You can also [download a sample configuration](/assets/developer-docs/sdks/mobile-sdks/client-configs/kameleoon-client-swift.plist) file.

These are the keys you can set:

| Key                                                                                                                              | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | Default value        |
| -------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| `refreshIntervalMinute` / `refresh_interval_minute` <Badge color="green" size="sm">optional</Badge>                              | Specifies the refresh interval, in minutes, for the SDK to fetch the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments. If left unspecified, the default interval is 60 minutes. Additionally, a [streaming mode](/developer-docs/feature-experimentation/technical-reference/technical-considerations/#streaming-premium-option) is available that uses server-sent events (SSE) to push new configurations to the SDK automatically and apply them in real-time.                                                                                 | `60` minutes         |
| `dataExpirationIntervalMinute` / `data_expiration_interval_minute` <Badge color="green" size="sm">optional</Badge>               | Designates the predefined time period, in minutes, that the SDK stores the visitor and their associated data. Each data instance is evaluated individually, allowing you to set the amount of time the SDK saves data before automatically deleting it. If no interval is specified, the SDK does not automatically delete data from the device.                                                                                                                                                                                                                                                                                                                                                            | `Date.distantFuture` |
| `defaultTimeoutMillisecond` / `default_timeout_millisecond` <Badge color="green" size="sm">optional</Badge>                      | Specifies the time interval, in milliseconds, that it takes for network requests from the SDK to time out. Set the value to `30000` milliseconds (30 seconds) or more if you do not have a stable connection. Some methods have additional parameters for method-specific timeouts, but if you do not specify them explicitly, the default value is used.                                                                                                                                                                                                                                                                                                                                                   | `10000` ms           |
| `trackingIntervalMillisecond` / `tracking_interval_millisecond` <Badge color="green" size="sm">optional</Badge>                  | Specifies the interval for tracking requests, in milliseconds. All visitors who were evaluated for any feature flag or had data flushed will be included in this tracking request, which is performed once per interval. The minimum value is `1000` ms and the maximum value is `5000` ms.                                                                                                                                                                                                                                                                                                                                                                                                                 | `1000` ms            |
| `environment` / `environment` <Badge color="green" size="sm">optional</Badge>                                                    | For customers using multi-environment experimentation and feature flagging, this option specifies which feature flag configuration to use. By default, each feature flag has the options `production`, `staging`, and `development`. If not specified, the default value is `production`. [More information](/user-manual/experimentation/feature-experimentation/configure-your-feature-flags/manage-environments).                                                                                                                                                                                                                                                                                        | `nil`                |
| `isUniqueIdentifier` / `is_unique_identifier` <Badge color="green" size="sm">optional</Badge>                                    | Indicates that the specified `visitorCode` is a unique identifier.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | `false`              |
| `networkDomain` / `network_domain` <Badge color="green" size="sm">optional</Badge>                                               | Custom domain used by SDKs for outgoing requests, often for proxying. Must be a valid domain (e.g., example.com or sub.example.com). Invalid formats default to Kameleoon's value.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | `nil`                |
| `defaultDataFile` / `default_datafile` <Badge color="green" size="sm">optional</Badge>                                           | The `default_datafile` feature ensures the Kameleoon SDK is always **READY** by providing a fallback configuration when no cached data file exists. Developers can preload a valid configuration by fetching it from `https://sdk-config.kameleoon.eu/v3/<sitecode>` and passing it as `default_datafile` during initialization. When a `dateModified` timestamp (in milliseconds) is provided and is newer than the cached version, the SDK will use the default datafile instead of the cached version. **If `dateModified` is omitted, the default datafile is only applied when no cached version exists**. This ensures the SDK always has a valid configuration, whether default, cached, or updated. | `nil`                |
| `activityTrackingIntervalMillisecond` / `activity_tracking_interval_millisecond` <Badge color="green" size="sm">optional</Badge> | Defines the interval at which activity events are sent. Modifying this parameter can have side effects. Check [this section](#using-activitytrackingintervalmillisecond) before using it. The minimum and default value is `15 000` ms. Setting this value to `0` disables periodic activity tracking; in this case, only a single activity event is sent at application startup.                                                                                                                                                                                                                                                                                                                           | `15 000` ms          |

<Note>
  If you specify a `visitorCode` and set the `isUniqueIdentifier` parameter to `true`, the SDK methods use the `visitorCode` value as the unique visitor identifier, which is useful for [cross-device experimentation](/developer-docs/cross-device-experimentation). The SDK links the flushed data to the visitor that is associated with the specified identifier.

  The `isUniqueIdentifier` can be useful in other edge-case scenarios, such as when you can't access the anonymous `visitorCode` that was originally assigned to the visitor, but you have access to an internal ID that is connected to the anonymous visitor through session merging.
</Note>

##### Using `activityTrackingIntervalMillisecond`

The `activityTrackingIntervalMillisecond` parameter is designed to help reduce battery consumption and network usage. However, changing its value can have **significant side effects** that you should carefully consider.

Review its impact on the following features:

1. **[Elapsed time triggers](/user-manual/assets/triggers/create-a-trigger#visiting-behavior)**
   * If the configured elapsed time is shorter than the tracking interval, the trigger will not fire as expected.

2. **[Elapsed time segments](/user-manual/assets/segments/create-a-segment#visiting-behavior)**
   * If the elapsed time is shorter than the tracking interval, users may not be included in the segment as intended.

3. **[Time spent goals](/user-manual/assets/goals/create-a-goal#time-spent)**
   * If the elapsed time is shorter than the tracking interval, the goal may never be reached.

4. **[Time elapsed since last visit in the results page](/user-manual/experiment-analytics/analyze-results/results-page-settings#filter-audience)**
   * Measurements for "time elapsed since last visit" become less precise when the elapsed time is close to or below the tracking interval.

5. **[Visits count](/user-manual/experiment-analytics/troubleshooting/data-discrepancies#how-visits-and-visitors-are-counted)**
   * A new visit is created after 30 minutes of inactivity. If the tracking interval is longer than 30 minutes, a new visit will be created at each tracking interval.

<Warning>
  Setting `activityTrackingIntervalMillisecond` to `0` disables periodic activity tracking entirely. In this configuration, only a single activity event is sent at application startup, which renders all of the features listed above unusable.
</Warning>

#### Initialize the Kameleoon Client

After you've set up the SDK in your application, you must create the Kameleoon Client. A Client is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you need to run an experiment.

```swift theme={null}
import kameleoonClient

let visitorCode = "visitorCode"
let siteCode = "a8st4f59bj"
do {
    // pass client configuration as an argument
    let config = try KameleoonClientConfig(
        clientId: "clientId", // optional
        clientSecret: "clientSecret", // optional
        refreshIntervalMinute: 15, // optional, 60 minutes by default
        dataExpirationIntervalMinute: 60*24*365, // optional, `Date.distantFuture` by default
        defaultTimeoutMillisecond: 10_000, // optional, 10_000 milliseconds by default
        trackingIntervalMillisecond: 500, // optional, 1000 milliseconds by default
        environment: "production", // optional
        isUniqueIdentifier: false, // optional, false by default. Set to true if the visitorCode corresponds to your customer's unique userId.
        networkDomain: "example.com", // optional, nil by default
        defaultDataFile: "{...}", // optional, nil by default
        activityTrackingIntervalMillisecond: 20_000 // optional, 15_000 milliseconds by default
    )
    let kameleoonClient = try KameleoonClientFactory.create(
        siteCode: siteCode,
        visitorCode: visitorCode, // optional
        config: config // optional
    )
} catch KameleoonError.visitorCodeInvalid {
  // Provided visitor code is invalid
} catch KameleoonError.siteCodeIsEmpty {
  // Indicates that provided site code is empty
} catch {
    // Unexpected error occurred
}

do {
    // read client configuration from a file 'kameleoon-client-swift.plist'
    // visitor code isn't provided, so SDK generates a random visitor code which it will use in the future
    let kameleoonClient = try KameleoonClientFactory.create(siteCode: siteCode)
} catch KameleoonError.visitorCodeInvalid {
    // Provided visitor code is invalid
} catch {
    // Unexpected error occurred
}
```

The `KameleoonClientFactory.create()` method initializes the client, but the client is not immediately ready for use. The client must retrieve the current configuration of experiments and feature flags (along with their traffic repartition) from a Kameleoon remote server. This retrieval requires the client to have network access, which is not always available. Until the Kameleoon Client is fully ready, you should not attempt to run other methods in the Kameleoon iOS SDK. After the client fetches the first configuration of feature flags, it periodically refreshes the configuration. If the refresh fails for any reason, the Kameleoon client continues to function using the previous configuration.

You can use the `.ready` public getter to check if the Kameleoon client initialization is finished.

Alternatively, a **helper callback** can encapsulate the logic of experiment triggering and variation implementation. The best approach (`.ready` or **callback**) depends on preferences and the use case. Using `.ready` is recommended when the SDK is expected to be ready for use soon. For example, `.ready` is appropriate when running an experiment on a dialog that would be accessible only after a few seconds or minutes of navigation within the app. A callback is recommended when there is a high probability that the SDK will still be initializing when the experiment is reached. For example, an experiment visible at the launch of the app should use a callback that makes the application wait until either the SDK is ready or a specified timeout has expired.

<Note>
  It's your responsibility as the app developer to ensure the client is ready before calling any methods. A good practice is to always assume that the app user should be left out of the experiment if the Kameleoon client is not yet ready. This exclusion is easy to do, as it corresponds to the implementation of the default reference variation logic as shown in the code sample above.
</Note>

You're now ready to implement feature management and features flags. See the [Reference](#reference) section for details about additional methods.

#### Best practices for initialization and usage

* Initializing [`KameleoonClient`](#create) as a singleton as early as possible after the application starts is recommended, as initialization may take some time. Since initialization is asynchronous, it does not block or delay the application startup process.
* Before using `KameleoonClient`, verify that it is initialized by calling the [`runWhenReady`](#runwhenready) method. Otherwise, attempts to use the client before it is ready will result in errors.
* ⚠️ Most key methods may throw errors, so proper exception handling is required. Be sure to review the documentation for each method you use to understand its potential errors.

<Tabs defaultTabIndex={0}>
  <Tab title="Swift">
    ```swift theme={null}
    // Initialize `KameleoonClient` on application startup and use it as a singleton later
    do {
        let kameleoonClient = try KameleoonClientFactory.create(siteCode: "<siteCode>");
    } catch {}

    // Example: Apply a discount percentage based on a feature flag variable's value
    func applyDiscountIfApplicable() {
        client.runWhenReady(timeoutMilliseconds: 1000) { ready in
            guard ready else { return }
            if let variation = try? client.getVariation(featureKey: "discount"),
               let discount = variation.variables["discount_value"]?.value as? Double {
                applyDiscount(value: discount)
            }
        }
    }
    ```
  </Tab>

  <Tab title="Swift (Async)">
    ```swift theme={null}
    // Initialize `KameleoonClient` on application startup and use it as a singleton later
    do {
        let kameleoonClient = try KameleoonClientFactory.create(siteCode: "<siteCode>");
    } catch {}

    // Example: Apply a discount percentage based on a feature flag variable's value
    func applyDiscountIfApplicable() async throws {
        try await client.runWhenReady(timeoutMilliseconds: 1000)
        if let variation = try client.getVariation(featureKey: "discount"),
           let discount = variation.variables["discount_value"]?.value as? Double {
            applyDiscount(value: discount)
        }
    }
    ```
  </Tab>
</Tabs>

#### Activating a feature flag

##### Retrieving a flag configuration

To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account.

To determine the status or variation of a feature flag for a specific user, you should use the [`getVariation()`](#getvariation) or [`isFeatureActive()`](#isfeatureactive) method to retrieve the configuration based on the `featureKey`.

The `getVariation()` method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the `featureKey` and `visitorCode`.

The `isFeatureActive()` method can be used if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options.

If your feature flag has associated variables (such as specific behaviors tied to each variation) `getVariation()` also enables you to access the [`Variation`](#variation) object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When `track=true`, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s [`tracking_interval_millisecond`](#additional-configuration). By default, this interval is set to 1000 milliseconds (1 second).

The `getVariation()` method allows you to control whether tracking is done. If `track=false`, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting `track=false` is helpful when using the `getVariations()` method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view [this article](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics)

##### Adding data points to target a user or filter / breakdown visits in reports

To target a user, ensure you've added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the [`addData()`](#adddata) method to add these data points to the user's profile.

To retrieve data points collected on other devices, use the [`getRemoteVisitorData()`](#getremotevisitordata) method. This method asynchronously fetches data from the servers. It is important to call `getRemoteVisitorData()` *before* retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.

To learn more about available targeting conditions, see the [detailed article on the subject](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device. See the complete list [here](/user-manual/experiment-analytics/analyze-results/results-page-settings#breakdown-audience).

If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's [Custom Data feature](#customdata). Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the [`flush()`](#flush) method to send the collected data to Kameleoon servers for analysis.

##### Tracking goal conversions

When a user completes a desired action (such as making a purchase), it is recorded as a conversion. To track conversions, use the [`trackConversion()`](#trackconversion) method and provide the required `goalId` parameter.

The conversion tracking request will be sent along with the next scheduled tracking request, which the SDK sends at regular intervals (defined by [`tracking_interval_millisecond`](#additional-configuration)). If you prefer to send the request immediately, use the [`flush()`](#flush) method with the parameter `instant=true`.

### Cross-device experimentation

To support visitors who access an app from multiple devices, Kameleoon allows the synchronization of previously collected visitor data across each of the visitor's devices and reconciliation of their visit history across devices through cross-device experimentation. Case studies and detailed information on how Kameleoon handles data across devices are available in the [article on cross-device experimentation](/developer-docs/cross-device-experimentation).

#### Synchronizing custom data across devices

Although custom mapping synchronization is used to align visitor data across devices, it is not always necessary. Below are two scenarios where custom mapping sync is not required:

**Same user ID across devices**
If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call the `getRemoteVisitorData()` method when you want to sync the data collected between multiple devices.

**Multi-server instances with consistent IDs**
In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with `getRemoteVisitorData()`) is sufficient without additional custom mapping sync.

Customers who need additional data can refer to the [`getRemoteVisitorData()`](#getremotevisitordata) method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the `visitorCode`, which can also be referred to as `userId`) is used consistently between the two devices for accurate data retrieval.

<Note>
  If you want to sync collected data in real time, you need to choose the scope **Visitor** for your custom data.
</Note>

<Tabs defaultTabIndex={0}>
  <Tab title="Swift">
    ```swift title="Device A" theme={null}
    // In this example, Custom data with index `90` was set to "Visitor" scope in Kameleoon.
    let visitorScopeCustomDataIndex = 90

    kameleoonClient.addData(CustomData(id: visitorScopeCustomDataIndex, values: "your data"))
    kameleoonClient.flush()
    ```

    ```swift title="Device B" theme={null}
    // Before working with the data, call `getRemoteVisitorData`.
    kameleoonClient.getRemoteVisitorData { result in
        // After calling, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
        // So, "your data" will be available to target and track the visitor.
    }
    ```
  </Tab>

  <Tab title="Swift (Async)">
    ```swift title="Device A" theme={null}
    // In this example, Custom data with index `90` was set to "Visitor" scope in Kameleoon.
    let visitorScopeCustomDataIndex = 90

    kameleoonClient.addData(CustomData(id: visitorScopeCustomDataIndex, values: "your data"))
    kameleoonClient.flush()
    ```

    ```swift title="Device B" theme={null}
    // Before working with the data, call `getRemoteVisitorData`.
    try await kameleoonClient.getRemoteVisitorData()
    // After calling, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
    // So, "your data" will be available to target and track the visitor.
    ```
  </Tab>
</Tabs>

#### Using custom data for session merging

[Cross-device experimentation](/developer-docs/cross-device-experimentation) allows for combining a visitor's history across each of their devices (history reconciliation). History reconciliation allows merging different visitor sessions into one. To reconcile visit history, use [`CustomData`](#customdata) to provide a unique identifier for the visitor. For more information, see the [dedicated documentation](/developer-docs/cross-device-experimentation/#activating-cross-device-history-reconciliation).

After cross-device reconciliation is enabled, calling [`getRemoteVisitorData()`](#getremotevisitordata) with the parameter `userId` retrieves all known data for a given user.

Sessions with the same identifier will always be shown the same variation in an experiment. In the Visitor view of your experiment's results pages, these sessions will appear as a single visitor.

The SDK configuration ensures that associated sessions always see the same variation of the experiment. However, there are some limitations regarding cross-device variation allocation. These limitations are outlined [here](/developer-docs/cross-device-experimentation#critical-points-and-practical-insights).

Follow the [activating cross-device history reconciliation](#cross-device-experimentation) guide to set up your custom data on the Kameleoon platform.

Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:

* `getRemoteVisitorData()` with passed `isUniqueIdentifier=true` to [`KameleoonClientConfig`](#additional-configuration) - to retrieve data for all linked visitors.
* [`trackConversion()`](#trackconversion) or [`flush()`](#flush) with passed `isUniqueIdentifier=true` to `KameleoonClientConfig` - to track some data for specific visitor that is associated with another visitor.

<Tip>
  As the custom data you use as the identifier must be set to **Visitor scope**, you need to use [cross-device custom data synchronization](/developer-docs/cross-device-experimentation) to retrieve the identifier with the [`getRemoteVisitorData()`](#getremotevisitordata) method on each device.
</Tip>

Here's an example of how to use custom data for session merging.

<Tabs defaultTabIndex={0}>
  <Tab title="Swift">
    ```swift theme={null}
    // In this example, `91` represents the Custom Data's index,
    // configured as a unique identifier in Kameleoon.
    let mappingIndex = 91;
    let featureKey = "ff123";

    // 0. Initializing anonymous KameleoonClient

    // Assume `anonymousVisitorCode` is the randomly generated ID for the visitor.
    let anonymousKameleoonClient = KameleoonClientFactory.create(
        siteCode: siteCode,
        visitorCode: anonymousVisitorCode
    )
    anonymousKameleoonClient.runWhenReady { result in
        // ...
    }

    // 1. Before the visitor is authenticated

    // Retrieve the variation for an unauthenticated visitor.
    let anonymousVariation = anonymousKameleoonClient.getVariation(featureKey)

    // 2. After the visitor is authenticated

    // Assume `userId` is the visitor code of the authenticated visitor.
    anonymousKameleoonClient.addData(CustomData(id: mappingIndex, values: userId))
    anonymousKameleoonClient.flush(instant: true)

    KameleoonClient userKameleoonClient = KameleoonClientFactory.create(
        siteCode: siteCode,
        visitorCode: userId,
        config: KameleoonClientConfig(
            isUniqueIdentifier: true // Indicate that `userId` is a unique identifier
        )
    )
    userKameleoonClient.runWhenReady { result in
        // ...
    }

    // 3. After the visitor has been authenticated

    // Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
    let userVariation = userKameleoonClient.getVariation(featureKey: featureKey)
    let isSameVariation = userVariation.key == anonymousVariation.key // true

    // The `userId` and `anonymousVisitorCode` are now linked and tracked as a single visitor.
    userKameleoonClient.trackConversion(goalId: 123, revenue: 10.0);

    // Additionally, the linked visitors will share all fetched remote visitor data.
    userKameleoonClient.getRemoteVisitorData { result in
        // ...
    }
    ```
  </Tab>

  <Tab title="Swift (Async)">
    ```swift theme={null}
    // In this example, `91` represents the Custom Data's index,
    // configured as a unique identifier in Kameleoon.
    let mappingIndex = 91;
    let featureKey = "ff123";

    // 0. Initializing anonymous KameleoonClient

    // Assume `anonymousVisitorCode` is the randomly generated ID for the visitor.
    let anonymousKameleoonClient = KameleoonClientFactory.create(
        siteCode: siteCode,
        visitorCode: anonymousVisitorCode
    )
    try await anonymousKameleoonClient.runWhenReady()

    // 1. Before the visitor is authenticated

    // Retrieve the variation for an unauthenticated visitor.
    let anonymousVariation = anonymousKameleoonClient.getVariation(featureKey)

    // 2. After the visitor is authenticated

    // Assume `userId` is the visitor code of the authenticated visitor.
    anonymousKameleoonClient.addData(CustomData(id: mappingIndex, values: userId))
    anonymousKameleoonClient.flush(instant: true)

    KameleoonClient userKameleoonClient = KameleoonClientFactory.create(
        siteCode: siteCode,
        visitorCode: userId,
        config: KameleoonClientConfig(
            isUniqueIdentifier: true // Indicate that `userId` is a unique identifier
        )
    )
    try await userKameleoonClient.runWhenReady()

    // 3. After the visitor has been authenticated

    // Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
    let userVariation = userKameleoonClient.getVariation(featureKey: featureKey)
    let isSameVariation = userVariation.key == anonymousVariation.key // true

    // The `userId` and `anonymousVisitorCode` are now linked and tracked as a single visitor.
    userKameleoonClient.trackConversion(goalId: 123, revenue: 10.0);

    // Additionally, the linked visitors will share all fetched remote visitor data.
    try await userKameleoonClient.getRemoteVisitorData()
    ```
  </Tab>
</Tabs>

In this example, the application has a login page. Since the user ID is unknown at the moment of login, an anonymous visitor automatically generated by the SDK is used. The visitor code can be retrieved with the [`getVisitorCode()`](#getvisitorcode) method. After the user logs in, the anonymous visitor is associated with the user ID and used as a unique identifier for the visitor.

### Using a custom bucketing key

By default, Kameleoon uses a unique, anonymous visitor ID (`visitorCode`) to assign users to feature flag variations. This ID is typically generated and stored on the user's device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). However, in certain scenarios you may need to ensure all users of the same organization see the same variant of a feature flag.

The **Custom Bucketing Key** option allows you to override this default behavior by providing your own custom identifier for bucketing. This override ensures that Kameleoon's assignment logic uses your specified key instead of the default `visitorCode`.

#### Use cases

Using a custom bucketing key is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:

* **Account-level or organizational experiments:** For B2B products or scenarios where you want to assign all users from the same organization to the same variation, you can use an identifier like an `accountId`. Custom bucketing keys are crucial for A/B testing features that impact an entire team or company.

By implementing a custom bucketing key, you ensure greater consistency and accuracy in your experiments, leading to more reliable results and a better user experience.

#### Technical details

When you configure a custom bucketing key for a feature flag, you provide Kameleoon with a specific identifier from your application's data:

```swift theme={null}
try? kameleoonClient.addData(CustomData(id: index, values: "newVisitorCode"))
```

* **Providing the custom key:** You provide your custom identifier to the Kameleoon SDK using the [`addData()`](#adddata) method. In this method, you will pass your chosen custom bucketing key as a [`CustomData`](#customdata) object. Here, `newVisitorCode` refers to the identifier you wish to use for your bucketing (for example, the new `userId` or `accountId`).

<Warning>
  For the custom bucketing key to function correctly, it must also be defined and configured for the feature flag during the flag creation or editing process. Without this corresponding configuration, the SDK's bucketing will not apply your custom key. For detailed instructions on how to set this up in Kameleoon, refer to this [article](/user-manual/experimentation/feature-experimentation/create-and-manage-flags/create-a-feature-flag#Advanced_Flag_Settings).
</Warning>

* **Bucketing logic:** Once a custom bucketing key is provided through the `addData()` method, all hash calculations for assigning users to variations will use this `newVisitorCode` (your custom key) instead of the default `visitorCode`. Using the `newVisitorCode` means that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
* **Data tracking and analytics:** It's crucial to note that while the `newVisitorCode` (your custom key) is used for bucketing decisions, **all subsequent data (tracking events and conversions, for example) is sent and associated with the *original* `visitorCode`.** This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment's broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Your original visitor data remains intact for comprehensive reporting.

#### Technical requirements

To effectively use a custom bucketing key:

* The key must be a `String`.
* It must be unique for the entity you intend to bucket (for example, if using a `userId`, each user's ID should be unique).
* The key must be available to the SDK at the exact moment the feature flag decision is evaluated for that user or request.

### Targeting conditions

The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions this SDK supports, see [use visit history to target users](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

You can also use your own [external data to target users](/developer-docs/apis/data-api-rest/tutorials/storing-and-retrieving-external-data-to-target-users).

### Logging

The SDK generates logs to reflect various internal processes and issues.

#### Log levels

The SDK supports configuring limiting logging by a log level.

```swift theme={null}
// The `none` log level does not allow logging.
KameleoonLogger.logLevel = .none

// The `ERROR` log level only allows logging issues that may affect the SDK's main behaviour.
KameleoonLogger.logLevel = .error

// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
KameleoonLogger.logLevel = .warning

// The `INFO` log level allows logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
KameleoonLogger.logLevel = .info

// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular diagnostic output.
// This information is not intended for end-user interpretation but can be sent to support
// to assist with internal troubleshooting.
KameleoonLogger.logLevel = .debug
```

#### Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.

<Note>
  Logging limiting by a log level is performed apart from the log handling logic.
</Note>

```swift theme={null}
public struct CustomLogger: Logging {
    let customLogger = Logger(subsystem: "com.yourcompany.app", category: "app")

    public func log(level: LogLevel, message: String) {
        switch level {
            case .error:
                customLogger.error("\(message)")
            case .warning:
                customLogger.warning("\(message)")
            case .info:
                customLogger.info("\(message)")
            case .debug:
                customLogger.debug("\(message)")
            default:
                break
        }
    }
}


// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
KameleoonLogger.logLevel = .debug // Optional, defaults to `LogLevel.WARNING`.
KameleoonLogger.logger = CustomLogger()
```

### Passing the visitor code to a WebView

In some cases, you may need to pass the **visitor code** from the native application to a WebView that uses [Engine.js](/developer-docs/web-experimentation/implementation-and-deployment/standard-implementation) or the web [JavaScript](/developer-docs/sdks/web-sdks/js-sdk) or [React](/developer-docs/sdks/web-sdks/react-js-sdk) SDKs. The following example demonstrates the recommended way to achieve this:

<Tabs defaultTabIndex={0}>
  <Tab title="SwiftUI">
    ```swift theme={null}
    struct WebView: UIViewRepresentable {

        let url: URL
        let kameleoonClient: KameleoonClient

        private let kameleoonCookieName = "kameleoonVisitorCode"

        func makeUIView(context: Context) -> WKWebView {
            let config = WKWebViewConfiguration()
            let webView = WKWebView(frame: .zero, configuration: config)
            let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
            let cookie = makeVisitorCookie()

            cookieStore.setCookie(cookie) {
                webView.load(URLRequest(url: url))
            }

            return webView
        }

        func updateUIView(_ webView: WKWebView, context: Context) {}

        private func makeVisitorCookie() -> HTTPCookie {
            let properties: [HTTPCookiePropertyKey: Any] = [
                .domain: ".example.com",
                .path: "/",
                .name: kameleoonCookieName,
                .value: kameleoonClient.visitorCode,
                .secure: true,
                .expires: Date(timeIntervalSinceNow: 60 * 60 * 24 * 365)
            ]
            return HTTPCookie(properties: properties)!
        }
    }
    ```
  </Tab>

  <Tab title="SwiftUI (iOS 26+)">
    ```swift theme={null}
    struct WebView: View {

        let url: URL
        let kameleoonClient: KameleoonClient

        private let websiteDataStore: WKWebsiteDataStore

        private let kameleoonCookieName = "kameleoonVisitorCode"

        @State private var page: WebPage

        init(url: URL, kameleoonClient: KameleoonClient) {
            self.url = url
            self.kameleoonClient = kameleoonClient

            let websiteDataStore = WKWebsiteDataStore.default()
            var configuration = WebPage.Configuration()
            configuration.websiteDataStore = websiteDataStore

            self.websiteDataStore = websiteDataStore
            _page = State(initialValue: WebPage(configuration: configuration))
        }

        var body: some View {
            WebView(page)
                .webViewBackForwardNavigationGestures(.enabled)
                .task(id: url) {
                    let cookieStore = websiteDataStore.httpCookieStore
                    let properties: [HTTPCookiePropertyKey: Any] = [
                        .domain: ".example.com",
                        .path: "/",
                        .name: kameleoonCookieName,
                        .value: kameleoonClient.visitorCode,
                        .secure: true
                    ]

                    if let cookie = HTTPCookie(properties: properties) {
                        await cookieStore.setCookie(cookie)
                    }

                    page.load(URLRequest(url: url))
                }
        }
    }
    ```
  </Tab>
</Tabs>

### Apple privacy compliance

Starting May 1st, 2024, Apple requires apps that include a third-party SDK, such as the Kameleoon iOS SDK, that include a privacy manifest file. The latest version of the SDK is code-signed, compliant, and includes a valid manifest file with the SDK. No action is required if you're using the Kameleoon iOS SDK version 4.2 or later.

## Reference

This is the full reference documentation for the Kameleoon iOS (Swift) SDK.

### Initialization

Once you have [installed the SDK](#installation) in your application, you must initialize Kameleoon. All of your application's interactions with the SDK, such as triggering an experiment, are accomplished using this Kameleoon client object.

#### create()

Call this method before any others to initialize the SDK. This method is in `KameleoonClientFactory`. `create()` creates an instance of `KameleoonClient` to manage all interactions between the SDK and your app.

You can customize the SDK's behavior (for example, the environment, the credentials) by providing a [configuration object](#additional-configuration). Otherwise, the SDK tries to find your configuration file and will use it instead.

```swift theme={null}
let visitorCode = "visitorCode"
let siteCode = "a8st4f59bj"
do {
    // pass client configuration as an argument
    let config = try KameleoonClientConfig(
        clientId: "clientId", // optional
        clientSecret: "clientSecret", // optional
        refreshIntervalMinute: 15, // optional, 60 minutes by default
        dataExpirationIntervalMinute: 60*24*365, // optional, `Date.distantFuture` by default
        defaultTimeoutMillisecond: 10_000, // optional, 10_000 milliseconds by default
        trackingIntervalMillisecond: 500, // optional, 1000 milliseconds by default
        environment: "production", // optional
        isUniqueIdentifier: false, // optional, false by default. Set to true if the visitorCode corresponds to your customer's unique userId.
        networkDomain: "example.com", // optional, nil by default
        defaultDataFile: "{...}", // optional, nil by default
        activityTrackingIntervalMillisecond: 20_000 // optional, 15_000 milliseconds by default
    )
    let kameleoonClient = try KameleoonClientFactory.create(
        siteCode: siteCode,
        visitorCode: visitorCode, // optional
        config: config // optional
    )
} catch KameleoonError.visitorCodeInvalid {
  // Provided visitor code is invalid
} catch KameleoonError.siteCodeIsEmpty {
  // Indicates that provided site code is empty
} catch {
    // Unexpected error occurred
}

do {
    // read client configuration from a file 'kameleoon-client-swift.plist'
    // visitor code isn't provided, so SDK generates a random visitor code which will be used in the future
    let kameleoonClient = KameleoonClientFactory.create(siteCode: siteCode)
} catch KameleoonError.visitorCodeInvalid {
  // Provided visitor code is invalid
} catch KameleoonError.siteCodeIsEmpty {
  // Indicates that provided site code is empty
} catch {
    // Unexpected error occurred
}
```

##### Parameters

| Name                                                        | Type                     | Description                                                                                                                                                                                                                                                 | Default |
| ----------------------------------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| siteCode <Badge color="red" size="sm">required</Badge>      | `String`                 | A [unique key](/user-manual/faq#how-do-i-find-my-sitecode) identifying the Kameleoon project used with the SDK.                                                                                                                                             |         |
| visitorCode <Badge color="green" size="sm">optional</Badge> | `String?`                | An optional visitor identifier. If available, use your internal **user ID**; otherwise, the SDK will generate one automatically.                                                                                                                            | `nil`   |
| config <Badge color="green" size="sm">optional</Badge>      | `KameleoonClientConfig?` | Optional SDK configuration. If provided, it is used instead of reading from an external [configuration file](#additional-configuration). If not provided, the SDK attempts to read the file, but if the file is missing, it falls back to default behavior. | `nil`   |

##### Return value

| Type              | Description                                                                                                         |
| ----------------- | ------------------------------------------------------------------------------------------------------------------- |
| `KameleoonClient` | An instance of the `KameleoonClient` class that your app can then use to manage your experiments and feature flags. |

##### Exceptions thrown

| Type                                | Description                                                                                                         |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `KameleoonError.visitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
| `KameleoonError.siteCodeIsEmpty`    | Exception indicating that the specified site code is empty string which is invalid value.                           |

#### ready

For mobile SDKs, the Kameleoon Client's initialization is not immediate. The SDK needs to perform a server call to retrieve the current configuration for all active experiments. Check if the SDK is ready by calling this method before triggering an experiment. Alternatively, you can use the [`runWhenReady()`](#runwhenready) method with a callback.

```swift theme={null}
let ready = kameleoonClient.ready
```

##### Return value

| Name  | Type | Description                                                                                            |
| ----- | ---- | ------------------------------------------------------------------------------------------------------ |
| ready | Bool | Boolean representing the status of the SDK (true if fully initialized, false if not ready to be used). |

#### runWhenReady()

* 🔄 *Performs an asynchronous request (if the configuration is outdated or missing)*

For mobile SDKs, the `KameleoonClient` cannot initialize immediately, as it needs to perform a server call to retrieve the current configuration for all feature flags. Use the [`runWhenReady()`](#runwhenready) method to wait until the client is ready for use. Additionally, you can set a maximum timeout period to control how long the client will wait before it becomes ready.

If `ready=true`, the `KameleoonClient` is fully initialized, and feature flags will be evaluated and assigned their respective variations. If the result is `false` or a timeout occurs, the initialization will not complete.

The callback or asynchronous code should handle applying the reference variation, as a timeout will exclude the user from the feature flag.

<Warning>
  Since the initial configuration may require a server call, this mechanism is asynchronous. Therefore, you should either:

  * Provide a `completion` callback as an argument to the method to ensure you are notified when the `KameleoonClient` is fully initialized and ready for use.
  * Use asynchronous operations.
</Warning>

<Tabs defaultTabIndex={0}>
  <Tab title="Swift">
    ```swift theme={null}
    func applyRecommendedProductsVariation() {
        let defaultValue = 5 // Default control number for recommended products
        kameleoonClient.runWhenReady(timeoutMilliseconds: 1000) { ready in
            guard ready else {
                applyVariation(recommendedProductsNumber: defaultValue)
                return
            }
            let variation = try? kameleoonClient.getVariation(featureKey: "featureKey")
            let recommendedProductsNumber = variation.variables["recommendedProductsNumber"]?.value as? Int ?? defaultValue

            applyVariation(recommendedProductsNumber: recommendedProductsNumber)
        }
    }
    ```

    ##### Arguments

    | Name                                                                | Type             | Description                                                                                                                                                        | Default                                                                                              |
    | ------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- |
    | timeoutMilliseconds <Badge color="green" size="sm">optional</Badge> | `Int`            | Timeout for the initialization process                                                                                                                             | [`defaultTimeoutMillisecond`](#create) or [`default_timeout_millisecond`](#additional-configuration) |
    | callback <Badge color="red" size="sm">required</Badge>              | `(Bool) -> Void` | Callback object. It is a lambda expression that will get a `Bool` argument representing whether the `KameleoonClient` became ready before the timeout was reached. |                                                                                                      |
  </Tab>

  <Tab title="Swift (Async)">
    <Warning>
      A common mistake is calling `async` functions with `try?` or inside a **nested** `do-catch` block **without rethrowing `CancellationError`**. This can interfere with task cancellation, causing unexpected behavior.
      To ensure correct task cancellation, avoid using `try?` or `do-catch` around `async` functions unless you explicitly rethrow `CancellationError`.
    </Warning>

    ```swift theme={null}
    func applyRecommendedProductsVariation() async throws {
        let defaultValue = 5 // Default control number for recommended products

        try await kameleoonClient.runWhenReady(timeoutMilliseconds: 1000)

        let variation = try kameleoonClient.getVariation(featureKey: "featureKey")
        let recommendedProductsNumber = variation.variables["recommendedProductsNumber"]?.value as? Int ?? defaultValue

        applyVariation(recommendedProductsNumber: recommendedProductsNumber)
    }
    ```

    ##### Parameters

    | Name                                                                | Type  | Description                            | Default                                                                                              |
    | ------------------------------------------------------------------- | ----- | -------------------------------------- | ---------------------------------------------------------------------------------------------------- |
    | timeoutMilliseconds <Badge color="green" size="sm">optional</Badge> | `Int` | Timeout for the initialization process | [`defaultTimeoutMillisecond`](#create) or [`default_timeout_millisecond`](#additional-configuration) |

    ##### Errors thrown

    | Type                         | Description                                                     |
    | ---------------------------- | --------------------------------------------------------------- |
    | `KameleoonError.sdkNotReady` | Exception indicating that the SDK is not fully initialized yet. |
  </Tab>
</Tabs>

### Feature flags and variations

#### isFeatureActive()

* *📨 Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

<Note>
  This method was previously called `activateFeature`, which was removed in SDK version `4.0.0`.
</Note>

To activate a feature toggle, call this method. `isFeatureActive()` accepts `featureKey` as a required argument to check if the specified feature will be active for a visitor.

If a visitor has never been associated with this feature flag, this method returns a random boolean value (`true` if the user should be shown this feature, otherwise `false`). If the visitor is already registered with this feature flag, the method returns the previous `featureFlag` value.

Ensure you implement error handling as shown in the example code to catch potential errors.

<Note>
  Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as `isFeatureActive()`, `getVariation()` or `getVariations()`.

  Use the default `true` value for the `track` parameter when you expose visitors to a variation and need to count them. Set the `track` parameter to `false` only if you call these methods before you expose visitors.

  For example, if you call `getVariations()` to retrieve all variations before you expose visitors, set the `track` parameter to `false`. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.

  Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
</Note>

```swift theme={null}
let featureKey = "new_checkout"
var hasNewCheckout = false

do {
    hasNewCheckout = try kameleoonClient.isFeatureActive(featureKey: featureKey)
    // disabling tracking
    hasNewCheckout = kameleoonClient.isFeatureActive(featureKey: featureKey, track: false);
} catch {
    switch error {
        case KameleoonError.sdkNotReady:
            // Exception indicating that the SDK has not completed its initialization yet.
            hasNewCheckout = false
        case KameleoonError.Feature.notFound:
		    // The feature key is not in the configuration file that has been fetched by the SDK.
            hasNewCheckout = false
        default:
            // Any other error.
            hasNewCheckout = false
    }
}

if hasNewCheckout
{
  // Implement new checkout code here
}
```

<Warning>
  The `isFeatureActive()` method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the **Then, for everyone else serve** default state. If you select **Off** for this default state, the method always returns `false` even when the master feature flag is **On**.
</Warning>

##### Arguments

| Name       | Type     | Description                                                                                 |
| ---------- | -------- | ------------------------------------------------------------------------------------------- |
| featureKey | `String` | The key of the feature you want to expose to a user. This field is required.                |
| track      | `Bool`   | An optional parameter to enable or disable feature evaluation tracking (`true` by default). |

##### Return value

| Type   | Description                                              |
| ------ | -------------------------------------------------------- |
| `Bool` | Value of the feature that is registered for the visitor. |

##### Errors thrown

| Type                              | Description                                                                                                                                                                                                                                                                                  |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `KameleoonError.sdkNotReady`      | Exception indicating that the SDK is not fully initialized.                                                                                                                                                                                                                                  |
| `KameleoonError.Feature.notFound` | Exception indicating that the requested feature ID has not been found in the SDK's internal configuration. This exception usually means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed in the web-application). |

#### getVariation()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves the [`Variation`](#variation) assigned to a given visitor for a specific feature flag.

This method takes a `visitorCode` and `featureKey` as mandatory arguments. The `track` argument is optional and defaults to `true`.

It returns the assigned `Variation` for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default `Variation` for the given feature flag.

Ensure that proper error handling is implemented in your code to manage potential exceptions.

<Note>
  The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
</Note>

```swift theme={null}
let featureKey = "featureKey"
var variation: Types.Variation?
do {
    variation = try kameleoonClient.getVariation(featureKey: featureKey)
    // disabling tracking
    variation = kameleoonClient.getVariation(featureKey: featureKey, track: false);
} catch {
    switch error {
        case KameleoonError.sdkNotReady:
            // Exception indicating that the SDK has not completed its initialization yet.
        case KameleoonError.Feature.notFound:
		    // The feature key is not in the configuration file that has been fetched by the SDK.
        case KameleoonError.Feature.environmentDisabled:
		    // The feature flag is disabled for the environment.
        default:
            // Any other error.
    }
}

let title = variation?.variables["title"].value

switch variation?.key {
    case "on":
        // Main variation key is selected for visitorCode
    case "alternative_variation":
        // Alternative variation key
    default:
        // Default variation key
}
```

##### Parameters

| Name                                                        | Type     | Description                                                                    | Default |
| ----------------------------------------------------------- | -------- | ------------------------------------------------------------------------------ | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `String` | Unique identifier of the visitor.                                              |         |
| `featureKey` <Badge color="red" size="sm">required</Badge>  | `String` | Key of the feature you want to expose to a visitor.                            |         |
| `track` <Badge color="green" size="sm">optional</Badge>     | `Bool`   | An optional parameter to enable or disable tracking of the feature evaluation. | `true`  |

##### Return value

| Type        | Description                                                                           |
| ----------- | ------------------------------------------------------------------------------------- |
| `Variation` | An assigned [`Variation`](#variation) to a given visitor for a specific feature flag. |

##### Errors thrown

| Type                                         | Description                                                                                                                                                                                                                                                           |
| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `KameleoonError.visitorCodeInvalid`          | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.                                                                                                                                                   |
| `KameleoonError.Feature.notFound`            | Exception indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed in the application). |
| `KameleoonError.Feature.environmentDisabled` | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                          |

#### getVariations()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves a map of [`Variation`](#variation) objects assigned to a given visitor across all feature flags.

This method iterates over all available feature flags and returns the assigned `Variation` for each flag associated with the specified visitor. It takes `onlyActive` and `track` as optional arguments.

* If `onlyActive` is set to `true`, the method `getVariations()` will return feature flags variations provided the user is not bucketed with the `off` variation.
* The `track` parameter controls whether or not the method will track the variation assignments. By default, it is set to `true`. If set to `false`, the tracking will be disabled.

The returned map consists of feature flag keys as keys and their corresponding `Variation` as values. If no variation is assigned for a feature flag, the method returns the default `Variation` for that flag.

Proper error handling should be implemented to manage potential exceptions.

<Note>
  The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
</Note>

```swift theme={null}
do {
    let variations = kameleoonClient.getVariations();
    // only active variations
    let variations = kameleoonClient.getVariations(onlyActive: true);
    // disable tracking
    let variations = kameleoonClient.getVariations(track: false);
} catch KameleoonError.sdkNotReady {
    // Exception indicating that the SDK has not completed its initialization yet.
}
```

##### Parameters

| Name                                                         | Type   | Description                                                                                                       | Default |
| ------------------------------------------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------- | ------- |
| `onlyActive` <Badge color="green" size="sm">optional</Badge> | `Bool` | An optional parameter indicating whether to return variations for active (`true`) or all (`false`) feature flags. | `false` |
| `track` <Badge color="green" size="sm">optional</Badge>      | `Bool` | An optional parameter to enable or disable tracking of the feature evaluation.                                    | `true`  |

##### Return value

| Type                      | Description                                                                                                                         |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `Dict<String, Variation>` | Map that contains the assigned [`Variation`](#variation) objects of the feature flags using the keys of the corresponding features. |

##### Errors thrown

| Type                         | Description                                          |
| ---------------------------- | ---------------------------------------------------- |
| `KameleoonError.sdkNotReady` | Indicates that the SDK is not yet fully initialized. |

#### setForcedVariation()

The method allows you to programmatically assign a specific [`Variation`](#variation) to a user, bypassing the standard evaluation process. This is especially valuable for controlled experiments where the usual evaluation logic is not required or must be skipped. It can also be helpful in scenarios like debugging or custom testing.

When a **forced** variation is set, it overrides Kameleoon's real-time evaluation logic. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set `forceTargeting=false` instead.

A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.

The method may throw exceptions under certain conditions (e.g., invalid parameters, user context, or internal issues). Proper exception handling is essential to ensure that your application remains stable and resilient.

```swift theme={null}
let experimentId = 9516
do {
    // Forcing the variation "on" for the experiment 9516 for the visitor
    try kameleoonClient.setForcedVariation(experimentId: experimentId, variationKey: "on")

    // Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment
    try kameleoonClient.setForcedVariation(experimentId: experimentId, variationKey: "on", forceTargeting: false)

    // Resetting the forced variation for the experiment 9516 for the visitor
    try kameleoonClient.setForcedVariation(experimentId: experimentId, variationKey: nil);
} catch {
    // Handling the KameleoonError, KameleoonError.Feature and common Error
}
```

##### Parameters

| Name                                                             | Type     | Description                                                                                                                                                                 | Default |
| ---------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `experimentId` <Badge color="red" size="sm">required</Badge>     | `Int`    | **Experiment Id** that will be targeted and selected during the evaluation process.                                                                                         |         |
| `variationKey` <Badge color="red" size="sm">required</Badge>     | `String` | **Variation Key** corresponding to a `Variation` that should be forced as the returned value for the experiment. If the value is `nil`, the forced variation will be reset. |         |
| `forceTargeting` <Badge color="green" size="sm">optional</Badge> | `Bool`   | Indicates whether targeting for the experiment should be forced and skipped (`true`) or applied as in the standard evaluation process (`false`).                            | `true`  |

##### Errors thrown

| Type                                        | Description                                                                                                                                                                                                                                           |
| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `KameleoonError.sdkNotReady`                | Indicates that the SDK is not yet fully initialized.                                                                                                                                                                                                  |
| `KameleoonError.Feature.experimentNotFound` | Exception indicating that the requested experiment id has not been found in the SDK's internal configuration. This is usually normal and means that the rule's corresponding experiment has not yet been activated on Kameleoon's side.               |
| `KameleoonError.Feature.variationNotFound`  | Exception indicating that the requested variation key(id) has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side. |

<Info>
  In most cases, only the basic error, `KameleoonError/KameleoonError.Feature`, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including `Error`.
</Info>

#### evaluateAudiences()

* 📨 *Sends Tracking Data to Kameleoon*

This method evaluates visitors against all available Audiences Explorer segments and tracks those who match.

`evaluateAudiences()` should be called **after all relevant visitor data has been set or updated**, and **just before** getting a feature variation or checking a feature flag. This approach ensures that the visitor is evaluated against the most current data available, allowing for accurate audience assignment based on all criteria.

After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.

```swift theme={null}
do {
    try kameleoonClient.evaluateAudiences();
} catch {
    // Handling the errors
}
```

##### Errors thrown

| Type                         | Description                                          |
| ---------------------------- | ---------------------------------------------------- |
| `KameleoonError.sdkNotReady` | Indicates that the SDK is not yet fully initialized. |

<Info>
  In most cases, only the basic error, `KameleoonError/KameleoonError.Feature`, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including `Error`.
</Info>

#### getFeatureList()

<Tip>
  If you want to iterate over all feature flags and call [`getVariation()`](#getvariation) on each, use the [`getVariations()`](#getvariations) method instead.
</Tip>

Returns a list of feature flag keys currently available for the SDK.

```swift theme={null}
let allFeatureList = kameleoonClient.getFeatureList()
```

##### Return value

| Type       | Description               |
| ---------- | ------------------------- |
| `[String]` | List of feature flag keys |

#### getDataFile()

<Tip>
  To evaluate all feature flags, use [`getVariations()`](#getvariations). This method is more efficient than calling `DataFile` and iterating through flags with [`getVariation()`](#getvariation).
</Tip>

Returns the current SDK configuration as a [`DataFile`](#datafile) object.

```swift theme={null}
do {
    let dataFile = try kameleoonClient.getDataFile()
} catch KameleoonError.sdkNotReady {
    // Exception indicates that the SDK has not completed its initialization yet.
} catch {
    // Handling the KameleoonError, KameleoonError.Feature and common Error
}
```

##### Return value

| Type       | Description                                                  |
| ---------- | ------------------------------------------------------------ |
| `DataFile` | The [`DataFile`](#datafile) containing the SDK configuration |

##### Errors thrown

| Type                         | Description                                          |
| ---------------------------- | ---------------------------------------------------- |
| `KameleoonError.sdkNotReady` | Indicates that the SDK is not yet fully initialized. |

### Goals

#### trackConversion()

* 📨 *Sends Tracking Data to Kameleoon*

Use this method to track conversions. This method requires `goalId` to track conversion on this particular [goal](/user-manual/assets/goals/create-a-goal). In addition, this method also accepts `revenue`, `metadata` and `negative` arguments.

The `trackConversion()` method doesn't return any value. This method is non-blocking as the server call is made asynchronously.

```swift theme={null}
let goalId = 83023
kameleoonClient.trackConversion(goalId: goalId, revenue: 10.0)

kameleoonClient.trackConversion(goalId: goalId, revenue: 10.0, metadata: CustomData(id: 1, values: "metadata"))
```

##### Parameters

| Name                                                       | Type                           | Description                                                                                                                      | Default |
| ---------------------------------------------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `goalId` <Badge color="red" size="sm">required</Badge>     | `Int`                          | ID of the goal.                                                                                                                  |         |
| `revenue` <Badge color="green" size="sm">optional</Badge>  | `Double`                       | Revenue of the conversion.                                                                                                       | `0`     |
| `negative` <Badge color="green" size="sm">optional</Badge> | `Bool`                         | Defines if the revenue is positive or negative.                                                                                  | `false` |
| `metadata` <Badge color="green" size="sm">optional</Badge> | `CustomData... / [CustomData]` | Metadata of the conversion. [Must be defined beforehand in the Kameleoon App](/user-manual/assets/goals/create-a-goal#metadata). | `[]`    |

<Note>
  metadata values are accessible through [raw data exports](/user-manual/experiment-analytics/analyze-results/results-page-actions#Export) and [the results page](/user-manual/experiment-analytics/analyze-results/goal-metadata).

  If the `metadata` parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the [`addData()`](#adddata) method. If the parameter is omitted, Kameleoon will use the last tracked values for those [`CustomData`](#customdata) prior to the conversion and within the same visit.

  Kameleoon will only consider the metadata values that are explicitly passed as parameters to the `trackConversion()` method.

  In the example below, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value 'Amex Credit Card').

  ```swift theme={null}
  kameleoonClient.addData([CustomData(id: 5, values: "Credit Card"), CustomData(id: 9, "Express Delivery")]);
  kameleoonClient.trackConversionWithOptParams(goalId: 1000, metadata: CustomData(5, "Amex Credit Card"));
  ```
</Note>

### Events

#### updateConfigurationHandler()

The `updateConfigurationHandler()` method allows you to handle the event when configuration has updated data. It takes one input parameter, **handler**. The handler that will be called when the configuration is updated using a real-time configuration event.

<Note>
  This handler only fires when the SDK is running in [streaming mode](/developer-docs/feature-experimentation/technical-reference/technical-considerations#streaming-premium-option) (server-sent events). It is **not** called for configuration refreshes performed in the default polling mode (`refreshIntervalMinute`).
</Note>

```swift theme={null}
kameleoonClient.updateConfigurationHandler {
  // configuration was updated
}
```

##### Parameters

| Name      | Type                     | Description                                                                                              |
| --------- | ------------------------ | -------------------------------------------------------------------------------------------------------- |
| `handler` | `Optional<(() -> Void)>` | The handler that will be called when the configuration is updated using a real-time configuration event. |

### Visitor data

#### visitorCode

Returns unique visitor code used in SDK.

```swift theme={null}
let visitorCode = kameleoonClient.visitorCode
```

##### Return value

| Type     | Description                                            |
| -------- | ------------------------------------------------------ |
| `String` | String representing a unique visitor code used in SDK. |

#### addData()

The `addData()` method adds [targeting data](#data-types) to storage so other methods can use the data to decide whether or not to target the current visitor.

The `addData()` method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the [`flush()`](#flush) method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered by the `flush()`.

The [`trackConversion()`](#trackconversion) method also sends out any previously associated data, just like the `flush()`. The same holds true for [`getVariation()`](#getvariation) and [`getVariations()`](#getvariations) methods if an experimentation rule is triggered.

<Tip>
  Each visitor can only have one instance of associated data for most data types. However, [`CustomData`](#customdata) is an exception. Visitors can have one instance of associated `CustomData` per index.
</Tip>

```swift theme={null}
// Add a single data item (tracked by default)
kameleoonClient.addData(CustomData(index: 1, values: "value"))

// Add multiple data items (tracked by default)
kameleoonClient.addData(
    CustomData(index: 20, values: "value"),
    Geolocation(country: "France")
)

// Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
kameleoonClient.addData(
    track: false,
    CustomData(index: 20, values: "value"),
    Geolocation(country: "France")
)
```

##### Parameters

| Name                                                    | Type                                 | Description                                                                                                                                                                                  | Default value |
| ------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `track` <Badge color="green" size="sm">optional</Badge> | `Bool`                               | Specifies whether the added data is eligible for tracking. When set to `false`, the data is stored locally and used only for targeting evaluation; it is not sent to the Kameleoon Data API. | `true`        |
| `data` <Badge color="red" size="sm">required</Badge>    | `KameleoonData... / [KameleoonData]` | Collection of Kameleoon data types.                                                                                                                                                          |               |

#### flush()

* 📨 *Sends Tracking Data to Kameleoon*

The `flush()` method collects the Kameleoon data linked to the visitor. It then sends a tracking request, along with all data added using the `addData` method that has not yet been sent using one of [these methods](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics). `flush()` is non-blocking as the server call is made asynchronously.

`flush` provides control over when data associated with a given `visitorCode` is sent to the servers. For instance, if `addData()` is called a dozen times, sending data to the server each time `addData()` is invoked would be inefficient. Call `flush()` once.

```swift theme={null}
kameleoonClient.addData(CustomData(id: 20, values: "true", "20"))
kameleoonClient.addData(Conversion(goalId: 32, revenue: 10.0, negative: false))

kameleoonClient.flush() // Interval tracking (most performant way for tracking)
kameleoonClient.flush(instant: true) // Instant tracking
```

##### Parameters

| Name    | Type   | Description                                                                                                                                                                                                                                                                                                                                                                                 |
| ------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| instant | `Bool` | Boolean flag indicating whether the data should be sent instantly (`true`) or according to the default tracking interval (`false`) set with the SDK parameter `trackingIntervalMillisecond` in [`KameleoonClientConfig`](/developer-docs/sdks/mobile-sdks/ios-sdk#initialize-the-kameleoon-client) or [`tracking_interval_millisecond`](#additional-configuration). This field is optional. |

##### Errors thrown

| Type                         | Description                                                         |
| ---------------------------- | ------------------------------------------------------------------- |
| `KameleoonError.sdkNotReady` | Error indicating that the SDK has not completed its initialization. |

#### getRemoteData()

* 🔄 *Performs an asynchronous request*

<Note>
  This method was previously called `retrieveDataFromRemoteSource`, which was removed in SDK version `4.0.0` release.
</Note>

Use this method to retrieve data from a remote Kameleoon server based on the active `siteCode` and the `key` argument (or the active `visitorCode` if the `key` is omitted). The `visitorCode` and `siteCode` are specified in `KameleoonClientFactory.create()`. Data can be stored quickly and conveniently on highly scalable remote servers using the Kameleoon Data API. The application can then retrieve the data using this method.

<Warning>
  Since a server call is required, this mechanism is asynchronous. Therefore, you should either:

  * Provide a `completion` callback as an argument to the method to ensure you are notified when the data has been successfully fetched.
  * Use asynchronous operations.
</Warning>

<Tabs defaultTabIndex={0}>
  <Tab title="Swift">
    ```swift theme={null}
    struct Test1: Decodable {
      let value: String

      private enum CodingKeys: String, CodingKey {
        case value = "json_value"
      }
    }

    kameleoonClient.getRemoteData(key: "test") { (result: Result<Test1, Error>) in
        switch result {
            case .success(let test1):
                // test1 is a decoded value for Test1 type
            case .failure:
                // error includes information about request's failure
        }
    }

    kameleoonClient.getRemoteData(key: "test") { (data: Result<Data, Error>) in
        switch result {
            case .success(let data):
                if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
                    print(json)
                }
            case .failure:
                // error includes information about request's failure
        }
    }
    ```

    ##### Parameters

    | Name                                                     | Type                                    | Description                                               | Default |
    | -------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------- | ------- |
    | key <Badge color="green" size="sm">optional</Badge>      | `String`                                | The key that the data you want to get is associated with. | `""`    |
    | completion <Badge color="red" size="sm">required</Badge> | `(Result<T: Decodable, Error>) -> Void` | The callback that processes the received data.            |         |
  </Tab>

  <Tab title="Swift (Async)">
    <Warning>
      A common mistake is calling `async` functions with `try?` or inside a **nested** `do-catch` block **without rethrowing `CancellationError`**. This can interfere with task cancellation, causing unexpected behavior.
      To ensure correct task cancellation, avoid using `try?` or `do-catch` around `async` functions unless you explicitly rethrow `CancellationError`.
    </Warning>

    ```swift theme={null}
    struct Test1: Decodable {
      let value: String

      private enum CodingKeys: String, CodingKey {
        case value = "json_value"
      }
    }

    Task {
        do {
            let test1: Test1 = try await kameleoonClient.getRemoteData(key: "test")
            // test1 is a decoded value for Test1 type
        } catch {
            // handle error
        }
    }

    Task {
        do {
            let data: Data = try await kameleoonClient.getRawRemoteData(key: "test")
            if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
                print(json)
            }
        } catch {
            // handle error
        }
    }
    ```

    ##### Parameters

    | Name                                                | Type     | Description                                               | Default |
    | --------------------------------------------------- | -------- | --------------------------------------------------------- | ------- |
    | key <Badge color="green" size="sm">optional</Badge> | `String` | The key that the data you want to get is associated with. | `""`    |

    ##### Return Value

    | Type        | Description                                                                                                            |
    | ----------- | ---------------------------------------------------------------------------------------------------------------------- |
    | `Decodable` | A [`Decodable`](https://developer.apple.com/documentation/swift/decodable) object containing the parsed fetched value. |

    ##### Errors thrown

    | Type    | Description                                            |
    | ------- | ------------------------------------------------------ |
    | `Error` | Indicates that the request has failed due to an error. |
  </Tab>
</Tabs>

#### getRemoteVisitorData()

* 🔄 *Performs an asynchronous request*

`getRemoteVisitorData()` is an asynchronous method for retrieving Kameleoon Visits Data for the visitor from the Kameleoon Data API. The method adds the data to storage for other methods to use when making targeting decisions.

Data obtained using this method plays an important role when you want to:

* use data collected from other devices.
* access a user's history, such as custom data collected during previous visits.

Read [this article](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation) for a better understanding of possible use cases.

<Note>
  By default, `getRemoteVisitorData()` automatically retrieves the latest stored custom data with `scope=Visitor` and attaches them to the visitor without the need to call the method `addData()`. It is particularly useful for [synchronizing custom data between multiple devices](/developer-docs/sdks/web-sdks/nodejs-sdk#synchronizing-custom-data-across-devices).

  Checking only for failed results is recommended. However, if necessary, it can be verified that the data has been added to the visitor and is available for targeting purposes (or for debugging, though using [logging](#logging) is better for debugging). Additionally, data can be managed manually if the `addData=false` parameter is passed.
</Note>

<Warning>
  Since a server call is required, this mechanism is asynchronous. Therefore, you should either:

  * Provide a `completion` callback as an argument to the method to ensure you are notified when the data has been successfully fetched and added to the visitor.
  * Use asynchronous operations.
</Warning>

<Tabs defaultTabIndex={0}>
  <Tab title="Swift">
    ```swift theme={null}
    // Fetch visitor data and automatically add it
    kameleoonClient.getRemoteVisitorData { result in
        switch result {
            case .success(let visitorData):
                // visitorData includes all retrieved data that was added for the visitor
            case .failure:
                // Handle the error, which contains information about the request failure
        }
    }

    // Fetch visitor data without automatically adding it
    kameleoonClient.getRemoteVisitorData(addData: false) { result in
        switch result {
            case .success(let visitorData):
                // visitorData includes all retrieved data that was added for the visitor
            case .failure:
                // Handle the error, which contains information about the request failure
        }
    }

    // Fetch a custom list of data types
    let filter = Types.RemoteVisitorDataFilter(
        previousVisitAmount: 25, currentVisit: true, conversions: true, experiments: true, geolocation: true
    )
    kameleoonClient.getRemoteVisitorData(filter: filter) { result in
        switch result {
            case .success(let visitorData):
                // visitorData includes all retrieved data that was added for the visitor
            case .failure:
                // Handle the error, which contains information about the request failure
        }
    }
    ```

    ##### Parameters

    | Name                                                     | Type                                       | Description                                                                                                                                                      | Default                           |
    | -------------------------------------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
    | filter <Badge color="green" size="sm">optional</Badge>   | `RemoteVisitorDataFilter`                  | Filter that selects which data should be retrieved from visit history. By default, the method retrieves `CustomData` from the current and latest previous visit. | `RemoteVisitorDataFilter.default` |
    | addData <Badge color="green" size="sm">optional</Badge>  | `Boolean`                                  | A boolean indicating whether the method should automatically add retrieved data for a visitor.                                                                   | `true`                            |
    | completion <Badge color="red" size="sm">required</Badge> | `(Result<[KameleoonData], Error>) -> Void` | The callback that processes the received visitor data.                                                                                                           |                                   |
  </Tab>

  <Tab title="Swift (Async)">
    <Warning>
      A common mistake is calling `async` functions with `try?` or inside a **nested** `do-catch` block **without rethrowing `CancellationError`**. This can interfere with task cancellation, causing unexpected behavior.
      To ensure correct task cancellation, avoid using `try?` or `do-catch` around `async` functions unless you explicitly rethrow `CancellationError`.
    </Warning>

    ```swift theme={null}
    // Fetch visitor data and automatically add it
    Task {
        do {
            let visitorData = try await kameleoonClient.getRemoteVisitorData()
            // visitorData includes all retrieved data that was added for the visitor
        } catch {
            // Handle the error, which contains information about the request failure
        }
    }

    // Fetch visitor data without automatically adding it
    Task {
        do {
            let visitorData = try await kameleoonClient.getRemoteVisitorData(addData: false)
            // visitorData includes all retrieved data but was not added for the visitor
        } catch {
            // Handle the error, which contains information about the request failure
        }
    }

    // Fetch a custom list of data types
    Task {
        do {
            let filter = Types.RemoteVisitorDataFilter(
                previousVisitAmount: 25, currentVisit: true, conversions: true, experiments: true, geolocation: true
            )
            let visitorData = try await kameleoonClient.getRemoteVisitorData(filter: filter)
            // visitorData includes all retrieved data based on the specified filter
        } catch {
            // Handle the error, which contains information about the request failure
        }
    }
    ```

    ##### Parameters

    | Name                                                    | Type                      | Description                                                                                                                                                      | Default                           |
    | ------------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
    | filter <Badge color="green" size="sm">optional</Badge>  | `RemoteVisitorDataFilter` | Filter that selects which data should be retrieved from visit history. By default, the method retrieves `CustomData` from the current and latest previous visit. | `RemoteVisitorDataFilter.default` |
    | addData <Badge color="green" size="sm">optional</Badge> | `Boolean`                 | A boolean indicating whether the method should automatically add retrieved data for a visitor.                                                                   | `true`                            |

    ##### Return Value

    | Type              | Description                                           |
    | ----------------- | ----------------------------------------------------- |
    | `[KameleoonData]` | An array containing the fetched data for the visitor. |

    ##### Errors thrown

    | Type    | Description                                            |
    | ------- | ------------------------------------------------------ |
    | `Error` | Indicates that the request has failed due to an error. |
  </Tab>
</Tabs>

##### Using parameters with RemoteVisitorDataFilter

The `getRemoteVisitorData()` method offers flexibility by allowing you to define various parameters when retrieving data on visitors. Whether you're targeting based on goals, experiments, or variations, the same approach applies across all data types.

For example, suppose you want to retrieve data on visitors who completed a goal "Order transaction". You can specify parameters within the `getRemoteVisitorData()` method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the `previousVisitAmount` parameter to `5` and `conversions` to `true`.

The flexibility shown in this example is not limited to goal data. You can use parameters within the `getRemoteVisitorData()` method to retrieve data on a variety of visitor behaviors.

<Note>
  Here is the list of available `Types.RemoteVisitorDataFilter` options:

  | Name                                                                | Type   | Description                                                                                                                                                                                                                                                                                                                                              | Default |
  | ------------------------------------------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
  | previousVisitAmount <Badge color="green" size="sm">optional</Badge> | `Int`  | Number of previous visits to retrieve data from. Number between `1` and `25`                                                                                                                                                                                                                                                                             | `1`     |
  | currentVisit <Badge color="green" size="sm">optional</Badge>        | `Bool` | If true, current visit data will be retrieved                                                                                                                                                                                                                                                                                                            | `true`  |
  | customData <Badge color="green" size="sm">optional</Badge>          | `Bool` | If true, custom data will be retrieved.                                                                                                                                                                                                                                                                                                                  | `true`  |
  | conversions <Badge color="green" size="sm">optional</Badge>         | `Bool` | If true, conversion data will be retrieved.                                                                                                                                                                                                                                                                                                              | `false` |
  | experiments <Badge color="green" size="sm">optional</Badge>         | `Bool` | If true, experiment data will be retrieved.                                                                                                                                                                                                                                                                                                              | `false` |
  | geolocation <Badge color="green" size="sm">optional</Badge>         | `Bool` | If true, geolocation data will be retrieved.                                                                                                                                                                                                                                                                                                             | `false` |
  | kcs <Badge color="green" size="sm">optional</Badge>                 | `Bool` | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the [AI Predictive Targeting add-on](/user-manual/assets/segments/target-users-based-on-likelihood-to-convert)                                                                                                                                                                     | `false` |
  | visitorCode <Badge color="green" size="sm">optional</Badge>         | `Bool` | If true, Kameleoon will retrieve the `visitorCode` from the most recent visit and use it for the current visit. `visitorCode` is necessary if you want to ensure that the visitor, identified by their `visitorCode`, always receives the same variation across visits for [Cross-device experimentation](/developer-docs/cross-device-experimentation). | `true`  |
  | personalization <Badge color="green" size="sm">optional</Badge>     | `Bool` | If true, personalization data will be retrieved. `personalization` is required for the personalization condition                                                                                                                                                                                                                                         | `false` |
  | cbs <Badge color="green" size="sm">optional</Badge>                 | `Bool` | If true, Contextual Bandit score data will be retrieved.                                                                                                                                                                                                                                                                                                 | `false` |
</Note>

#### getVisitorWarehouseAudience()

* 🔄 *Performs an asynchronous request*

Retrieves all audience data associated with the visitor in your data warehouse. The optional `warehouseKey` parameter is typically your internal user ID. The `customDataIndex` parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the [warehouse targeting documentation](/user-manual/integrations/data-warehouses/bigquery/use-bigquery-as-a-source-audience-targeting) for additional details.

<Warning>
  Since a server call is required, this mechanism is asynchronous. Therefore, you should either:

  * Provide a `completion` callback as an argument to the method to ensure you are notified when the data has been successfully fetched and added to the visitor.
  * Use coroutines for asynchronous handling.

  Checking only for failed results is recommended. However, if necessary, it can be verified that the data has been added to the visitor and is available for targeting purposes (or for debugging, though using [logging](#logging) is better for debugging).
</Warning>

<Tabs defaultTabIndex={0}>
  <Tab title="Swift">
    ```swift theme={null}
    // Fetch visitor warehouse audience data
    kameleoonClient.getVisitorWarehouseAudience(customDataIndex: 10) { result in
        switch result {
            case .success(let customData):
                // Data was added. You can access it from `customData`
            case .failure:
                // Handle the error, which contains information about the request failure
        }
    }

    // Fetch visitor warehouse audience data with a specific warehouse key
    kameleoonClient.getVisitorWarehouseAudience(
        warehouseKey: "warehouseKey", customDataIndex: 10
    ) { result in
        switch result {
            case .success(let customData):
                // Data was added. You can access it from `customData`
            case .failure:
                // Handle the error, which contains information about the request failure
        }
    }
    ```

    ##### Parameters

    | Name                                                          | Type                                  | Description                                                                                             | Default |
    | ------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------- |
    | warehouseKey <Badge color="green" size="sm">optional</Badge>  | `String`                              | The unique key to identify the warehouse data (usually your internal user ID).                          | `""`    |
    | customDataIndex <Badge color="red" size="sm">required</Badge> | `Int`                                 | An integer representing the index of the custom data you want to use to target your BigQuery Audiences. |         |
    | completion                                                    | `(Result<CustomData, Error>) -> Void` | The callback that processes the received data.                                                          |         |
  </Tab>

  <Tab title="Swift (Async)">
    <Warning>
      A common mistake is calling `async` functions with `try?` or inside a **nested** `do-catch` block **without rethrowing `CancellationError`**. This can interfere with task cancellation, causing unexpected behavior.
      To ensure correct task cancellation, avoid using `try?` or `do-catch` around `async` functions unless you explicitly rethrow `CancellationError`.
    </Warning>

    ```swift theme={null}
    // Fetch visitor warehouse audience data
    Task {
        do {
            let customData = try await kameleoonClient.getVisitorWarehouseAudience(customDataIndex: 10)
            // Data was added. You can access it from `customData`
        } catch {
            // Handle the error, which contains information about the request failure
        }
    }

    // Fetch visitor warehouse audience data with a specific warehouse key
    Task {
        do {
            let customData = try await kameleoonClient.getVisitorWarehouseAudience(
                warehouseKey: "warehouseKey", customDataIndex: 10
            )
            // Data was added. You can access it from `customData`
        } catch {
            // Handle the error, which contains information about the request failure
        }
    }
    ```

    ##### Parameters

    | Name                                                          | Type     | Description                                                                                             | Default |
    | ------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------- | ------- |
    | warehouseKey <Badge color="green" size="sm">optional</Badge>  | `String` | The unique key to identify the warehouse data (usually your internal user ID).                          | `""`    |
    | customDataIndex <Badge color="red" size="sm">required</Badge> | `Int`    | An integer representing the index of the custom data you want to use to target your BigQuery Audiences. |         |

    ##### Return Value

    | Type         | Description                                                                                                                               |
    | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
    | `CustomData` | A [`CustomData`](#customdata) entry added for a visitor. Generally, you can ignore this value, but it may be useful for testing purposes. |

    ##### Errors thrown

    | Type    | Description                                            |
    | ------- | ------------------------------------------------------ |
    | `Error` | Indicates that the request has failed due to an error. |
  </Tab>
</Tabs>

#### setLegalConsent()

You must use this method to specify whether the visitor has given legal consent to use their personal data. Setting the `legalConsent` parameter to `false` limits the types of data that you can include in tracking requests. This method helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the [consent management policy](/user-manual/project-management/consent-management-policy).

##### Parameters

| Name         | Type    | Description                                                                                                                                                                                                             |
| ------------ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| legalConsent | boolean | A boolean value representing the legal consent status. `true` indicates the visitor has given legal consent; `false` indicates the visitor has never provided, or has withdrawn, legal consent. This field is required. |

```swift theme={null}
kameleoonClient.setLegalConsent(true)
```

### Data types

This section lists the data types supported by Kameleoon. Several standard data types are provided, as well as the `CustomData` type for defining custom data types.

#### Conversion

The `Conversion` data set stored here can be used to filter experiment and personalization reports by any goal associated with it.

<Tip>
  * Each visitor can have multiple `Conversion` objects.
  * You can find the `goalId` in the Kameleoon app.
</Tip>

| Name                                                       | Type                           | Description                                     | Default |
| ---------------------------------------------------------- | ------------------------------ | ----------------------------------------------- | ------- |
| `goalId` <Badge color="red" size="sm">required</Badge>     | `Int`                          | ID of the goal.                                 |         |
| `revenue` <Badge color="green" size="sm">optional</Badge>  | `Double`                       | Revenue of the conversion                       | `0`     |
| `negative` <Badge color="green" size="sm">optional</Badge> | `Bool`                         | Defines if the revenue is positive or negative. | `false` |
| `metadata` <Badge color="green" size="sm">optional</Badge> | `CustomData... / [CustomData]` | Metadata of the conversion.                     | `[]`    |

```swift theme={null}
kameleoonClient.addData(Conversion(goalId: 32, revenue: 10.0, negative: false))

kameleoonClient.addData(Conversion(goalId: 32, metadata: CustomData(id: 1, values: "metadata")))
```

#### CustomData

`CustomData` allows any type of data to be easily associated with each visitor. `CustomData` can then be used as a targeting condition in [segments](/user-manual/assets/segments/create-a-segment/) or as a filter/breakdown in experiment reports.

To learn more about custom data, please refer to this [article](/developer-docs/custom-data).

| Name                                                      | Type                      | Description                                                                                                                                                                             |        |
| --------------------------------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ |
| index/name <Badge color="red" size="sm">required</Badge>  | `Int`/`String`            | Index or Name of the custom data. **Either `index` or `name` must be provided** to identify the data.                                                                                   |        |
| overwrite <Badge color="green" size="sm">optional</Badge> | `Bool`                    | Flag to explicitly control how the values are stored and how they appear in reports. [See more](/developer-docs/custom-data#default-logic-when-overwrite-parameter-is-false-or-omitted) | `true` |
| values <Badge color="red" size="sm">required</Badge>      | `String...` or `[String]` | Values of the custom data to be stored.                                                                                                                                                 |        |

<Note>
  * Each visitor is allowed only one `CustomData` for each unique `index`. Adding another `CustomData` with the same `index` will replace the existing `CustomData`.
  * The custom data `index` can be found in the [Custom Data dashboard](/user-manual/assets/custom-data/manage-custom-data) under the “INDEX” column.
  * To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the **Use this data only locally for targeting purposes** option when creating custom data.
  * Adding a `CustomData` instance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
</Note>

```swift theme={null}
kameleoonClient.addData(CustomData(index: 1, values: "value"))

// With several values
kameleoonClient.addData(CustomData(index: 1, values: "value 1", "value 2"))

// To set the 'overwrite' flag to false
kameleoonClient.addData(CustomData(index: 1, overwrite: false, values: ["first value", "second value"]))

// To use a name instead of the index
kameleoonClient.addData(CustomData(name: "my-custom-data", values: "value"))
```

#### Device

<Note>
  Since iOS SDK `4.14.0`, the `Device` is automatically detected based on the value of [`UIDevice.current.userInterfaceIdiom`](https://developer.apple.com/documentation/uikit/uiuserinterfaceidiom). However, you can still manually override it if needed.
</Note>

Store information about the user's device.

| Name   | Type   | Description                                                            |
| ------ | ------ | ---------------------------------------------------------------------- |
| device | Device | List of devices: `phone`, `tablet`, `desktop`. This field is required. |

```swift theme={null}
try? kameleoonClient.addData(Device.desktop);
```

#### Geolocation

`Geolocation` contains the visitor's geolocation details.

| Name                                                         | Type                   | Description                                                                                                      |
| ------------------------------------------------------------ | ---------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `country` <Badge color="red" size="sm">required</Badge>      | `String`               | The country of the visitor.                                                                                      |
| `region` <Badge color="green" size="sm">optional</Badge>     | <nobr>`String?`</nobr> | The region of the visitor.                                                                                       |
| `city` <Badge color="green" size="sm">optional</Badge>       | <nobr>`String?`</nobr> | The city of the visitor.                                                                                         |
| `postalCode` <Badge color="green" size="sm">optional</Badge> | <nobr>`String?`</nobr> | The postal code of the visitor.                                                                                  |
| `latitude` <Badge color="green" size="sm">optional</Badge>   | `Double?`              | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.  |
| `longitude` <Badge color="green" size="sm">optional</Badge>  | `Double?`              | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |

<Tip>
  * Each visitor can have only one `Geolocation`. Adding a second `Geolocation` overwrites the first one.
</Tip>

```swift theme={null}
kameleoonClient.addData(Geolocation(country: "France", region: "Île-de-France", city: "Paris"));
```

### Returned Types

#### DataFile

The `DataFile` contains the SDK configuration details.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name           | Type                    | Description                                                                       |
| -------------- | ----------------------- | --------------------------------------------------------------------------------- |
| `featureFlags` | `[String: FeatureFlag]` | A map of [`FeatureFlag`](#featureflag) objects, keyed by feature flag keys.       |
| `dateModified` | `Int`                   | The timestamp (in milliseconds) indicating when the `DataFile` was last modified. |

```swift theme={null}
// Retrieves the dictionary of feature flags from the DataFile.
// The dictionary is keyed by feature flag identifiers, with each value being a FeatureFlag object.
let featureFlags = dataFile.featureFlags

// Retrieves the last modification timestamp of the DataFile.
// The value is an Int representing milliseconds since the Unix epoch.
let dateModified = dataFile.dateModified
```

#### FeatureFlag

The `FeatureFlag` represents a set of properties that define a feature flag itself — for example, its [`Variations`](#variation), [`Rules`](#rule), environment status, and other related details.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name                  | Type                  | Description                                                                |
| --------------------- | --------------------- | -------------------------------------------------------------------------- |
| `environmentEnabled`  | `Bool`                | Indicating whether the feature flag is enabled in the current environment. |
| `defaultVariationKey` | `String`              | The key of the default variation associated with the feature flag.         |
| `variations`          | `[String: Variation]` | A map of `Variation` objects, keyed by variation keys.                     |
| `rules`               | `[Rule]`              | A list of `Rule` objects                                                   |

```swift theme={null}
// Check whether the feature flag is enabled in the current environment
let isEnvironmentEnabled = featureFlag.environmentEnabled

// Retrieve the key of the default variation
let defaultVariationKey = featureFlag.defaultVariationKey

// Retrieve the default variation object
let defaultVariation = featureFlag.defaultVariation

// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
let variations = featureFlag.variations

// Retrieve all targeting rules associated with the feature flag
let rules = featureFlag.rules
```

#### Rule

The `Rule` represents a set of properties that define a rule itself — for example, its [`Variations`](#variation).

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name         | Type                  | Description                                            |
| ------------ | --------------------- | ------------------------------------------------------ |
| `variations` | `[String: Variation]` | A map of `Variation` objects, keyed by variation keys. |

```swift theme={null}
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
let variations = rule.variations
```

#### Variation

`Variation` contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).

| Name         | Type                 | Description                                                                                                                                                 |
| ------------ | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name         | `String`             | The name of the variation.                                                                                                                                  |
| key          | `String`             | The unique key identifying the variation.                                                                                                                   |
| id           | `Int`                | The ID of the assigned variation (or `-1` if it's the default variation).                                                                                   |
| experimentId | `Int`                | The ID of the experiment associated with the variation (or `-1` if default).                                                                                |
| variables    | `[String: Variable]` | A map containing the variables of the assigned variation, keyed by variable names. `variables` could be an empty collection if no variables are associated. |

<Note>
  * The `Variation` object provides details about the assigned variation and its associated experiment, while the [`Variable`](#variable) object contains specific details about each variable within a variation.
  * Ensure that your code handles the case where `id` or `experimentId` may be `-1`, indicating a default variation.
  * The `variables` map might be empty if no variables are associated with the variation.
</Note>

```swift theme={null}
// Retrieving the variation name
let variationName = variation.name

// Retrieving the variation key
let variationKey = variation.key

// Retrieving the variation id
let variationId = variation.id

// Retrieving the experiment id
let experimentId = variation.experimentId

// Retrieving the variables map
let variables = variation.variables
```

#### Variable

`Variable` contains information about a variable associated with the assigned variation.

| Name  | Type     | Description                                                                                                                                                           |
| ----- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| key   | `String` | The unique key identifying the variable.                                                                                                                              |
| type  | `String` | The type of the variable. Possible values: **BOOLEAN**, **NUMBER**, **STRING**, **JSON**.                                                                             |
| value | `Any?`   | The value of the variable, which can be of the following types: **Bool**, **Int**, **Double**, **String**, **\[String: Any]** (json object), **\[Any]** (json array). |

```swift theme={null}
// Retrieving the variables map
let variables = variation.variables

// Variable type can be retrieved for further processing
let type = variables["isDiscount"]?.type ?? ""

// Get the bool value of "isDiscount" (default to false if missing or not a Bool)
let isDiscount = variables["isDiscount"]?.value as? Bool ?? false

// Get the numeric value of "number" as an Int (default to 0 if missing or not numeric)
let number = (variables["number"]?.value as? NSNumber)?.intValue ?? 0

// Get the String value of "title" (default to an empty string if missing or not a String)
let title = variables["title"]?.value as? String ?? ""
```

### Deprecated methods

<Warning>
  These methods are deprecated and will be removed in SDK version `5.0.0`.
</Warning>

#### getFeatureVariationKey()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  Use [`getVariation()`](#getvariation) instead.
</Note>

Use this method to get the [feature variation](/user-manual/experimentation/feature-experimentation/configure-your-feature-flags/define-feature-variations) key for a specific user. This method takes a `featureKey` as a required argument to retrieve the variation key for the specified user.

If the visitor has never been associated with this feature flag, the SDK returns a randomly assigned variation key (according to the feature flag rules). If the visitor is already registered with this feature flag, this method returns the previous variation key. If the visitor does not match any of the rules, the default variation you defined in the Kameleoon app will be returned.

Ensure you set up proper error handling as shown in the example code to catch potential errors.

```swift theme={null}
let featureKey = "new_checkout"
var variationKey = ""

do {
	variationKey = try kameleoonClient.getFeatureVariationKey(featureKey: featureKey)
    switch variationKey {
        case "variation 1":
            // The visitor has been bucketed with variation 1 key
        case "variation 2":
            // The visitor has been bucketed with variation 2 key
        default:
            //The visitor has been bucketed with the default variation or is part of the unallocated traffic sample
    }
} catch {
    switch error {
        case KameleoonError.sdkNotReady:
            // Exception indicating that the SDK has not completed its initialization yet.
        case KameleoonError.Feature.notFound:
		    // The feature key is not in the configuration file that has been fetched by the SDK. Trigger the old checkout for this visitor.
        case KameleoonError.Feature.environmentDisabled:
		    // The feature flag is disabled for the environment.
        default:
            // Any other error.
    }
}
```

#### getActiveFeatureList()

<Note>
  Use [`getVariations()`](#getvariations) instead.
</Note>

To get the list of feature flag keys currently available and active for the visitor.

```swift theme={null}
let activeFeatureFlags = kameleoonClient.getActiveFeatureList()
```

##### Return value

| Type      | Description                                                |
| --------- | ---------------------------------------------------------- |
| \[String] | List of feature flag keys which are active for the visitor |

#### getActiveFeatures()

<Note>
  Use [`getVariations()`](#getvariations) instead.
</Note>

`getActiveFeatures` method retrieves information about the active feature flags that are available for the specified visitor code.

```swift theme={null}
let activeFeatures = kameleoonClient.getActiveFeatures()
```

##### Return value

| Type                        | Description                                                                                                                               |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `[String: Types.Variation]` | A dictionary that contains the visitor's assigned variations for each active feature using the keys of the corresponding active features. |

#### getFeatureVariable()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  - Use [`getVariation()`](#getvariation) instead.
  - This method was previously called `obtainFeatureVariable()`, which was removed in SDK version `4.0.0`.
</Note>

Call this method to get the [feature variable](/user-manual/experimentation/feature-experimentation/configure-your-feature-flags/define-feature-variables) of a variation key associated with a user.

This method takes `featureKey`, and `variableKey` as required arguments to get the variable of the variation key for a given user.

If a visitor has never been associated with this feature flag, the SDK returns a variable value for the variation key that it randomly assigns according to the feature flag rules. If the user is already registered with this feature flag, the SDK returns the variable value for the previously associated variation. If the user does not match any of the rules, the default variable is returned.

```swift theme={null}
String featureKey = "myFeature"
String variableKey = "myVariable"

try {
	let variable = kameleoonClient.getFeatureVariable(featureKey: featureKey, variableKey: variableKey)
    // your custom code, depending on variableValue
} catch {
    switch error {
        case KameleoonError.sdkNotReady:
            // Exception indicating that the SDK has not completed its initialization.
        case KameleoonError.Feature.notFound:
		    // The Feature Key is not in the configuration file that has been fetched by the SDK. Trigger the old checkout for this visitor.
        case KameleoonError.Feature.environmentDisabled:
		    // The feature flag is disabled for the environment.
        case KameleoonError.Feature.variableNotFound:
            // Exception indicating that the requested variable has not been found. Check that the variable's key matches the one in your code.

        default:
            // Any other error.
    }
}
```

##### Parameters

| Name        | Type   | Description                                                                     |
| ----------- | ------ | ------------------------------------------------------------------------------- |
| featureKey  | String | Identification key of the feature you want to retrieve. This field is required. |
| variableKey | String | Name of the variable you want to get a value for. This field is required.       |

##### Return value

| Type | Description                                                                                                                                             |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Any  | Data associated with this feature flag. The values can be `Int`, `String`, `Bool` or `Dictionary` (depending on the type defined on the web interface). |

##### Errors thrown

| Type                                           | Description                                                                                                                                                                                                                                                                                  |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| KameleoonError.sdkNotReady                     | Exception indicating that the SDK is not fully initialized.                                                                                                                                                                                                                                  |
| KameleoonError.Feature.notFound                | Exception indicating that the requested feature ID has not been found in the SDK's internal configuration. This exception usually means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed in the web-application). |
| KameleoonException.Feature.environmentDisabled | Exception indicating that the feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                                             |
| KameleoonError.Feature.variableNotFound        | Exception indicating that the requested variable wasn't found. Check that the variable's key in the Kameleoon app matches the key in your code.                                                                                                                                              |

#### getFeatureVariationVariables()

<Note>
  * Use [`getVariation()`](#getvariation) instead.
  * This method was previously called `getFeatureAllVariables`, which was removed in SDK version `4.0.0`.
</Note>

To retrieve all of the variables for a feature, call this method. You can modify your feature variables in the Kameleoon app.

This method takes `featureKey` as an argument. It returns data with the `[String: Any]` type, as defined on the web interface. It will throw an exception (`KameleoonError.Feature.notFound`) if the requested feature has not been found in the SDK's internal configuration.

```swift theme={null}
let featureKey = "myFeature"
let variationKey = "on"

do {
	allVariables = try kameleoonClient.getFeatureVariationVariables(featureKey: featureKey, variationKey: variationKey);
} catch KameleoonError.Feature.notFound {
	// The feature is not activated in Kameleoon.
} catch KameleoonError.Feature.environmentDisabled {
	// The feature flag is disabled for the environment.
} catch  {
    // This is a generic Exception handler that will handle all errors.
}
```

##### Parameters

| Name         | Type   | Description                                                                     |
| ------------ | ------ | ------------------------------------------------------------------------------- |
| featureKey   | String | Identification key of the feature you want to retrieve. This field is required. |
| variationKey | String | The key of the variation you want to retrieve. This field is required.          |

##### Return value

| Type           | Description                                                                                                                                             |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| \[String: Any] | Data associated with this feature flag. The values can be `Int`, `String`, `Bool` or `Dictionary` (depending on the type defined on the web interface). |

##### Errors thrown

| Type                                           | Description                                                                                                                                                                                                                                                                                                                                     |
| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| KameleoonError.sdkNotReady                     | Exception indicating that the SDK is not fully initialized.                                                                                                                                                                                                                                                                                     |
| KameleoonError.Feature.notFound                | Exception indicating that the requested feature ID has not been found in the SDK's internal configuration. This exception usually means that the feature flag has not been activated in the Kameleoon app (but code implementing the feature is already deployed in the web application).                                                       |
| KameleoonException.Feature.environmentDisabled | Exception indicating that the feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                                                                                                |
| KameleoonError.Feature.variationNotFound       | Exception indicating that the requested variation key has not been found in the SDK's internal configuration. This exception means that the feature flag has not yet been retrieved by the SDK, which may happen if the SDK is in [polling](/developer-docs/feature-experimentation/technical-reference/technical-considerations#polling) mode. |

```swift theme={null}
let featureKey = "myFeature"
let variationKey = "on"

do {
	allVariables = try kameleoonClient.getFeatureVariationVariables(featureKey: featureKey, variationKey: variationKey);
} catch KameleoonError.Feature.notFound {
	// The feature is not activated in Kameleoon.
} catch KameleoonError.Feature.environmentDisabled {
	// The feature flag is disabled for the environment.
} catch  {
    // This is a generic Exception handler that will handle all errors.
}
```
