Skip to main content

iOS SDK

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

Follow the Getting started section to walk through the installation process. To jump right into the code, see the SDK reference.

note

Kameleoon supports Swift versions 5.0 and later on the iOS platform. There is no planned support for earlier iOS applications (including earlier Swift versions and Objective-C apps). We provide a Universal Framework version compatible both with x86_64 (for the iOS Simulator) and ARM (for production deployment into the App Store).

Latest version of the Swift SDK: 4.1.4 (changelog).

Getting started

Follow this section to install and configure the iOS SDK in your iOS app.

Install the Swift client

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

With CocoaPods, paste the following code in your Podfile and replace YOUR_TARGET_NAME with the value for your app:

# Podfile
use_frameworks!

target 'YOUR_TARGET_NAME' do
pod 'kameleoonClient'
end

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

pod install

Additional configuration

To customize the SDK behavior, create a kameleoon-client-swift.plist configuration file in the root directory of your Xcode project. For example:

<project_root>/kameleoon-client-swift.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>environment</key>
<string>staging</string>
<key>refresh_interval_minute</key>
<integer>60</integer>
</dict>
</plist>

These are the keys you can set:

  • refresh_interval_minute (optional): Specifies the frequency, in minutes, that active experiments and feature flags are fetched from the Kameleoon servers. The initial fetch is performed on the first application launch and subsequent fetches are processed at the defined refresh interval. Once you launch an experiment, pause the experiment, or stop the experiment, the change won't propagate to each of your visitors' iOS devices until their next refresh. This means if you set the refresh interval to 30 minutes, it may take up to 30 minutes before all devices receive the update. If not specified, the default interval is 60 minutes.
  • data_expiration_interval_minute: Designates the predefined time period, in minutes, that the SDK stores the visitor and their associated data. Each data instance is evaluated individually. This allows you to set the amount of time the SDK saves the data before automatically deleting it. If no interval is specified, the SDK does not automatically delete data from the device. The default value is Date.distantFuture.
  • default_timeout_millisecond: Specifies the timeout, in milliseconds, for network requests from the SDK. Set the value to 30000 ms (30 seconds) or more if you do not have a stable connection. The default value is 10000 ms. Some methods have an additional parameter that you can use to override the default timeout for that particular method. If you do not specify the timeout for a method explicitly, the SDK uses this default value.
  • environment (optional): 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, development. If not specified, the default value is production. More information.

Initialize the Kameleoon Client

After you've the SDK in your application and set up the app properties, the next step is to 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.

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, `Data.distantFuture` by default
defaultTimeoutMillisecond: 10_000, // optional, 10_000 milliseconds by default
environment: "production" // optional
)
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 = 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 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, you can use a helper callback to encapsulate the logic of experiment triggering and variation implementation. The best approach (.ready or callback) depends on your preferences and use case. We recommend using .ready when you expect that the SDK will already be ready for use. For example, if you are running an experiment on a dialog that would be accessible only after a few seconds or minutes of navigation within the app. We recommend using the callback when there is a high probability that the SDK is still initializing when the experiment is accessible. For example, an experiment that is 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 is actually easy to do, because this corresponds to the implementation of the default reference variation logic. For example, as shown in the code sample above.

Reference

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

KameleoonClientFactory

create()

Call this method before any others to initialize the SDK. Create an instance of KameleoonClient to manage all interactions between the SDK and your app. If passed, the SDK uses the config argument as your configuration. Otherwise, the SDK tries to find and use your kameleoon-client-swift.plist configuration.

Arguments
NameTypeDescription
siteCodeStringSite code of the website you want to run experiments on. You can find this unique ID in the Kameleoon app. This field is required.
visitorCodeStringThe user's unique identifier. This field is optional. If the value is not specified, will be generated a random visitor code.
configKameleoonClientConfigConfiguration SDK object to use instead of the .pfile configuration file.
Return value
NameTypeDescription
kameleoonClientKameleoonClientInstance of KameleoonClient
Exceptions thrown
TypeDescription
KameleoonError.visitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.
KameleoonError.siteCodeIsEmptyException indicating that the specified site code is an empty string, which is invalid value.
Example code
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, `Data.distantFuture` by default
defaultTimeoutMillisecond: 10_000, // optional, 10_000 milliseconds by default
environment: "staging" // optional
)
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
}

KameleoonClient

ready

For mobile SDKs, the initialization of the Kameleoon Client 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() method with a callback.

Return value
NameTypeDescription
readyBoolBoolean representing the status of the SDK (true if fully initialized, false if not ready to be used).
Example code
let ready = kameleoonClient.ready

runWhenReady()

For mobile SDKs, the initialization of the Kameleoon Client is not immediate. The SDK needs to perform a server call to retrieve the current configuration for all active experiments. The runWhenReady() method of the KameleoonClient class allows you to pass a callback that will be executed as soon as the SDK is ready for use. It also allows you to specify a timeout.

The lambda given as the second argument to this method must have the signature (Bool) -> Void. The lambda will be called with the value true once the Kameleoon client is ready, and should contain code that triggers an experiment and implements variations. The lambda will be called with the value false if the specified timeout happens before the client is fully initialized. When this occurs, you can implement the "reference" variation, as the user will be excluded from the experiment entirely if a timeout takes place.

Arguments
NameTypeDescription
timeoutIntTimeout (in milliseconds). This field is optional. If not provided, it will use the default value of 2000 milliseconds.
callback(Bool) -> VoidCallback object. This field is required. It is a lambda expression that will get a Bool argument representing whether the Kameleoon Client became ready before the timeout was reached.
Example code
kameleoonClient.runWhenReady(1000) { success in
if (success)
{
let variationKey = try? kameleoonClient.getFeatureVariationKey(my_feature_key)
if variationKey == "off" {
// This is the default / reference number of products to display
recommendedProductsNumber = 2
} else if variationKey == "on" {
// We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8
}
}
else
{
variationKey = "off"
recommendedProductsNumber = 2
}
}

isFeatureActive()

note

This method was previously named activateFeature, which was removed in SDK version 4.0.0.

To activate a feature toggle, call this method. This method 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, this method returns the previous featureFlag value.

Make sure to set up proper error handling as shown in the example code to catch potential exceptions.

Arguments
NameTypeDescription
featureKeyStringThe key of the feature you want to expose to a user. This field is required.
Return value
TypeDescription
BoolValue of the feature that is registered for the visitor.
Exceptions thrown
TypeDescription
KameleoonError.sdkNotReadyException indicating that the SDK is not fully initialized yet.
KameleoonError.Feature.notFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This 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).
Example code
let featureKey = "new_checkout"
var hasNewCheckout = false

do {
hasNewCheckout = try kameleoonClient.isFeatureActive(featureKey: featureKey)
} 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 yet 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
}

getFeatureVariationKey()

Use this method to get the feature variation key for a specific user. This method takes a featureKey as 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.

Make sure you set up proper error handling as shown in the example code to catch potential exceptions.

Arguments
NameTypeDescription
featureKeyStringKey of the feature you want to expose to a user. This field is required.
Return value
TypeDescription
StringVariation key of the feature flag that is registered for the visitor.
Exceptions thrown
TypeDescription
KameleoonError.sdkNotReadyException indicating that the SDK has not completed its initialization yet.
KameleoonError.Feature.notFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This usually means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
KameleoonException.Feature.environmentDisabledException indicating that the feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
Example code
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 1 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 yet 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
}
}

getFeatureVariable()

note

This method was previously named obtainFeatureVariable(), which was removed in SDK version 4.0.0.

Call this method to get the feature variable 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 previously associated variation. If the user does not match any of the rules, the default variable is returned.

Arguments
NameTypeDescription
featureKeyStringIdentification key of the feature you want to retrieve. This field is required.
variableKeyStringName of the variable you want to get a value for. This field is required.
Return value
TypeDescription
AnyData associated with this feature flag. The values can be Int, String, Bool or Dictionary (depending on the type defined on the web interface).
Exceptions thrown
TypeDescription
KameleoonError.sdkNotReadyException indicating that the SDK is not fully initialized yet.
KameleoonError.Feature.notFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This 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.environmentDisabledException indicating that the feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
KameleoonError.Feature.variableNotFoundException indicating that the requested variable wasn't found. Check that the variable's key in the Kameleoon app matches the one in your code.
Example code
String featureKey = "myFeature"
String variableKey = "myVariable"

try {
let variable = kameleoonClient.getFeatureVariable(featureKey: featureKey, variableKey: variableKey)
// your custom code depending of variableValue
} 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 yet 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
}
}

getFeatureVariationVariables()

note

This method was previously named: getFeatureAllVariables, which was removed in SDK version 4.0.0 release.

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 one argument, featureKey. It returns the 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 internal configuration of the SDK.

Arguments
NameTypeDescription
featureKeyStringIdentification key of the feature you want to retrieve. This field is required.
variationKeyStringThe key of the variation you want to retrieve. This field is required.
Return value
TypeDescription
[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).
Exceptions thrown
TypeDescription
KameleoonError.sdkNotReadyException indicating that the SDK is not fully initialized yet.
KameleoonError.Feature.notFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This 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.environmentDisabledException indicating that the feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
KameleoonError.Feature.variationNotFoundException indicating that the requested variation key has not been found in the internal configuration of the SDK. This means that the feature flag has not yet been retrieved by the SDK. This may happen if the SDK is in polling mode.
Example code
let featureKey = "myFeature"
let variationKey = "on"

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

trackConversion()

Use this method to track conversions. This method requires goalId to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue.

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

Arguments
NameTypeDescription
goalIdIntID of the goal. This field is required.
revenueFloatRevenue of the conversion. This field is optional.
Errors thrown
TypeDescription
KameleoonError.sdkNotReadyError indicating that the SDK has not completed its initialization yet.
Example code
let goalId = 83023
kameleoonClient.trackConversion(goalId: goalId, revenue: 10.0)

addData()

The addData() method adds targeting data 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 method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered the flush. Note that the trackConversion method also sends out any previously associated data, just like the flush method. The same is true for getFeatureVariationKey and getFeatureVariable methods if an experimentation rule is triggered.

tip

Each visitor can only have one instance of associated data for most data types. However, CustomData is an exception. Visitors can have one instance of associated CustomData per customDataIndex.

Arguments
NameTypeDescription
dataKameleoonData... or [KameleoonData]One or more values conforming to the KameleoonData protocol.
Errors thrown
TypeDescription
KameleoonError.sdkNotReadyError indicating that the SDK is not fully initialized yet.
Example code
kameleoonClient.addData(CustomData(id: 20, values: "true", "20"))
kameleoonClient.addData(Conversion(goalId: 32, revenue: 10.0, negative: false))

kameleoonClient.addData([
CustomData(id: 20, values: "true", "20"),
Conversion(goalId: 32)
])

flush()

Data associated with the current user via addData() method is not sent immediately to the server. It is stored and accumulated until it is sent by the trackConversion() method or the flush() method. This allows the developer to exactly control when the data is flushed to our servers. For instance, if you call the addData() method a dozen times, it would waste resources to send data to the server after each addData() invocation, when you can simply call flush() once at the end.

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

Arguments
NameTypeDescription
completionHandlerOptional<(Bool) -> Void>Callback object. This field is optional. It is a lambda expression that will asynchronously get called with a Bool argument representing whether the flush() call succeeded or not.
Errors thrown
TypeDescription
KameleoonError.sdkNotReadyError indicating that the SDK has not completed its initialization yet.
kameleoonClient.addData(CustomData(id: 20, values: "true", "20"))
kameleoonClient.addData(Conversion(goalId: 32, revenue: 10.0, negative: false))
kameleoonClient.flush()

getFeatureList()

To get the list of feature flag keys that are currently available to the SDK, call this method.

Return value
TypeDescription
[String]List of feature flag keys
Example code
let allFeatureList = kameleoonClient.getFeatureList()

getActiveFeatureList()

note

This method is deprecated and will be removed in SDK version 5.0.0. Use getActiveFeatures instead.

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

Return value
TypeDescription
[String]List of feature flag keys which are active for the visitor
Example code
let activeFeatureFlags = kameleoonClient.getActiveFeatureList()

getActiveFeatures()

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

Return value
TypeDescription
[String: Types.Variation]A dictionary that contains the visitor's assigned variations for each active feature using the keys of the corresponding active features.
Example code
let activeFeatures = kameleoonClient.getActiveFeatures()

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 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.

Arguments
NameTypeDescription
legalConsentbooleanA 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.
Example code
kameleoonClient.setLegalConsent(true)

getRemoteData()

Use this method to retrieve data from a remote Kameleoon server based on your active siteCode and the key argument (or the active visitorCode if you omit the key). The visitorCode and siteCode are specified in KameleoonClientFactory.create. You can quickly and conveniently store data on our highly scalable remote servers using the Kameleoon Data API. Your application can then retrieve the data using this method.

note

Since a server call is required, this mechanism is asynchronous, and you must pass a completionHandler as an argument to the method.

Arguments
NameTypeDescription
keyStringThe key that the data you try to get is associated with. This field is optional.
completion(Result<T, Error>) -> Void where T: DecodableGeneric callback object. It is a lambda expression that will asynchronously get called with a T argument (must implement theDecodable protocol). Data can be used as the default type. This field is required.
Example code
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 represents with informaion 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 represents with informaion about request's failure
}
}
``
#### getRemoteVisitorData()

The `getRemoteVisitorData()` method retrieves the data assigned to a visitor for the **siteCode** specified in `KameleoonClientFactory.create()`, which is stored on a remote Kameleoon server. Optionally, this method can automatically add the retrieved data for the visitor (with to **addData** parameter). The data is usually stored on our remote servers using the Kameleoon Data API. This method combined with the availability of our highly scalable servers provides a convenient way to quickly store large amounts of data that you can later retrieve for each of your visitors.

##### Arguments

Name | Type | Description
--------- | ------- | -----------
addData | boolean | A boolean indicating whether the method should automatically add the retrieved data for a visitor. This field is optional. The default value is `true`.
completion | (Result<[KameleoonData], Error>) -> Void | A closure that takes an `Result<[KameleoonData], Error>` parameter to handle the result. Confirms that the data has been added to the visitor. If `addData` is false, it only indicates the value was retrieved.

##### Example code

```swift
kameleoonClient.getRemoteVisitorData { result in
switch result {
case .success(let visitorData):
// visitorData represents all data which was retrieved and added for the visitor
case .failure:
// error contains information about the reason for the request failure
}
}

kameleoonClient.getRemoteVisitorData(addData: false) { result in
switch result {
case .success(let visitorData):
// visitorData represents all data which was retrieved but not added for the visitor
case .failure:
// error contains information about the reason for the request failure
}
}

getVisitorWarehouseAudience()

Retrieves all audience data associated with the visitor in your data warehouse using the visitorCode and warehouseKey. The warehouseKey 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 for additional details. The method passes the result to the completionHandler as a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.

note

Since a server call is required, this mechanism is asynchronous, and you must pass a completionHandler as an argument to the method.

Arguments
NameTypeDescription
warehouseKeyStringThe unique key to identify the warehouse data (usually, your internal user ID). This field is optional.
customDataIndexIntAn integer representing the index of the custom data you want to use to target your Warehouse Audiences.
completion(Result<CustomData, Error>) -> VoidA closure that takes an Result<CustomData, Error> parameter to handle the result, confirming that the data has been added to the visitor.
Example code
kameleoonClient.getVisitorWarehouseAudience(customDataIndex: 10) { result in
switch result {
case .success(let customData):
// Data was added. You can access the data from the `customData` value.
case .failure:
// error contains information about failure of request
}
}

// If you need to specify a warehouse key
kameleoonClient.getVisitorWarehouseAudience(
warehouseKey: "warehouseKey",
customDataIndex: 10)
{ result in
switch result {
case .success(let customData):
// Data was added. You can access the data from the `customData` value.
case .failure:
// error contains information about failure of request
}
}

updateConfigurationHandler()

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

Arguments
NameTypeDescription
handlerOptional<(() -> Void)>The handler that will be called when the configuration is updated using a real-time configuration event.
Example code
kameleoonClient.updateConfigurationHandler {
// configuration was updated
}

Data

This section lists the data types supported by Kameleoon. We provide several standard data types as well as the CustomData type that allows you to define custom data types.

Conversion

Store information about conversion events.

NameTypeDescription
goalIDStringID of the goal. This field is required.
revenueFloatConversion revenue. This field is optional.
negativeBoolDefines if the revenue is positive or negative. This field is optional.
Example code
try? kameleoonClient.addData(Conversion(goalId: 32, revenue: 10.0, negative: false))

CustomData

Define your own custom data types in the Kameleoon app or the Data API and use them from the SDK.

NameTypeDescription
indexIntThe index a (a unique ID) of the custom data to store. This field is required.
valueStringValue of the custom data to store. This field is required.
valuesString... or [String]Value(s) of the custom data to store.
note

You can find the index (ID) for your custom data in the Kameleoon app, in the Custom data configuration page. Be careful: this index starts at 0, so the first custom data you create for a given site has an ID value of 0, not 1.

Example code
try? kameleoonClient.addData(CustomData(id: 1, value: "some custom value"))

try? kameleoonClient.addData(CustomData(id: 1, value: "first value", "second value"))

try? kameleoonClient.addData(CustomData(id: 1, values: ["first value", "second value"]))

Device

Store information about the user's device.

NameTypeDescription
deviceDeviceList of devices: phone, tablet, desktop. This field is required.
Example code
try? kameleoonClient.addData(Device.desktop);

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 supported by this SDK, see Use visit history to target users.

You can also use your own external data to target users.