Skip to main content

iOS SDK

Introduction

Welcome to the developer documentation for the Kameleoon Swift SDK! Our SDK gives you the possibility of running experiments and activating feature flags on native mobile iOS applications. Integrating our SDK into your applications is relatively easy, and its footprint (in terms of memory and network usage) is low.

You can refer to the SDK reference to check out all possible features of the SDK. Also make sure you check out our Getting started tutorial which we have prepared to walk you through the installation and implementation.

note

Note that Kameleoon only supports Swift (versions 5.0 and later) on the iOS platform. There is no planned support for older iOS applications (earlier Swift versions, or Objective-C).
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: 3.0.1 (changelog).

Getting started

This guide is designed to help you integrate our SDK in a few minutes and start running experiments in your iOS applications. This tutorial will explain the setup of a simple A/B test to change the number of recommended products based on different variations.

Creating an experiment

First, you must create an experiment in the Kameleoon back-office so that our platform is aware of the new A/B test you're planning to implement on your side. Make sure that mobile application type is chosen as shown below:

Server-side experiment

Upon successful creation of the experiment, you will need to get its ID to use in the SDK as an argument to the triggerExperiment() method.

Installing the SDK

Installing the Swift client

We currently support either CocoaPods or Swift Package Manager as methods of installation.

# Podfile
use_frameworks!

target 'YOUR_TARGET_NAME' do
pod 'kameleoonClient'
end

With CocoaPods, use the code to the right in your Podfile, replacing "YOUR_TARGET_NAME" with the correct value. Then in the Podfile directory, type:

$ pod install
dependencies: [
.package(url: "https://github.com/Kameleoon/client-swift.git", from("2.0.10"))
]

With Swift Package Manager, it is recommended to add a package dependency to your Xcode project. Select File > Swift Packages > Add Package Dependency and enter its repository URL: https://github.com/Kameleoon/client-swift.

Alternatively, modify your Package.swift file directly as shown in the example to the right.

Additional configuration

A .plist configuration file can also be used to customize the SDK behavior. A sample configuration file can be obtained here. This file should be installed in the root directory of your Xcode project, and should be named exactly kameleoon-client-swift.plist. With the current version of the Swift SDK, those are the available keys:

  • client_id: a client_id is required field for authentication to the Kameleoon service.
  • client_secret: a client_secret is required field for authentication to the Kameleoon service.
  • actions_configuration_refresh_interval: this specifies the refresh interval, in minutes, of the configuration for experiments and feature flags (the active experiments and feature flags are fetched from the Kameleoon servers). An initial fetch is performed on the first application launch, and subsequent fetches are processed at the defined interval. It means that once you launch an experiment, pause it, or stop it the changes can take (at most) the duration of this interval to be propagated to the end-user iOS devices. If not specified, the default interval is 60 minutes.
  • environment: an option specifying which feature flag configuration will be used, by default each feature flag is split into production, staging, development. If not specified, will be set to default value of production. More information

Initializing the Kameleoon Client

import kameleoonClient

let siteCode = "a8st4f59bj"
do {
// read client configiration from a file
let kameleoonClient = KameleoonClientFactory.create(sitecode: siteCode)

// pass client configiration as an argument
let config = try KameleoonClientConfig(clientId: "<CLIENT_ID>",
clientSecret: "<CLIENT_SECRET>")
let kameleoonClient = KameleoonClientFactory.create(sitecode: siteCode,
config: config)
} catch KameleoonError.credentialsNotFound {
// Credentials are not found in the config file or configuration object
}

After installing the SDK into your application and setting up an server-side experiment on Kameleoon's back-office, the next step is to create the Kameleoon client.

The code on the right gives a clear example. 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 will need to run an experiment.

While executing the KameleoonClientFactory.create() method initializes the client, on iOS it is not immediately ready for use. This is because the current configuration of experiments (along with their traffic repartition) has to be retrieved from a Kameleoon remote server. This requires network access, which is not always available. Until the Kameleoon client is fully ready, you should not try to run any other method in our SDK. Note that once the first configuration of experiments is fetched, it is then periodically refreshed, but even if the refresh fails for any reason, the Kameleoon client will still be ready and working (but on an outdated / previous configuration).

We provide the .ready public getter to know if the Kameleoon client initialization completed.

Alternatively, we provide a helper callback to encapsulate logic of experiment triggering and variation implementation. What approach (.ready or callback) is best to use depends on your own preferences and on the exact use case at hand. As a rule of thumb, we recommend using .ready when it is expected that the SDK will indeed be ready for use. For instance, if you are running an experiment on some dialog that would be accessible only after a few seconds / minutes of navigation within the application. And we recommend to use the callback when there is a high probability that the SDK is still in the process of initialization. For instance, an experiment that would take place at the launch of the application would be better treated with a callback that would make the application wait until either the SDK is ready or a specified timeout has expired.

note

It's the responsability of the developer to ensure proper logic of its application code within the context of A/B testing via Kameleoon. A good practice is to always assume that the application user can be left out of the experiment because 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, which should be done in any case. The code samples on the next paragraph show examples of such an approach.

Triggering an experiment

Running an A/B experiment on your iOS application means bucketing your users into several groups (one per variation). The SDK takes care of this bucketing (and the associated reporting) automatically.

Triggering an experiment by calling the triggerExperiment() method will register a random variation for a given visitorCode. If this visitorCode is already associated with a variation (most likely the user had already been exposed to the experiment previously), then it will return the previous variation associated with a given experiment.

note

By analogy with the server-side SDKs and the global Kameleoon terminology, we will use the term visitorCode throughout this documentation. However, for mobile SDKs this does not really represent a visitor but rather the current user of the device.
Obtaining a unique visitorCode on a mobile application significantly differs from the server-side equivalents of the Swift SDK, and is specific to your own implementation. You should almost always use the internal id for this user / account (database id, email...) as the visitorCode. In any case, visitorCode uniqueness must be guaranteed on your end - the SDK cannot check it.

note

The length of visitorCode is limited to 255 characters. Any excess characters will throw an error.

note

The triggerExperiment() method will quite often throw out errors. You should generally treat an error as if the user was bucketed into the reference. Some possible common errors:

  • Kameleoon client is not ready yet (discussed in previous section). This results in a KameleoonError.sdkNotReady error.
  • The experiment has not yet been launched on the Kameleoon platform (but the code implementing the experiment on the Swift application's side is already deployed). This results in a KameleoonError.experimentConfigurationNotFound error.
  • You used a targeting segment for this experiment, and the user does not match this targeting segment. This results in a KameleoonError.notTargeted error.
import kameleoonClient

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillEnterForeground(_ application: UIApplication) {
let kameleoonClient = kameleoonDelegate.kameleoonClient
let visitorCode = "1267576" // usually, this would be the internal ID of the current user
var variationID : Int
var recommendedProductsNumber : Int

if (kameleoonClient.ready) {
variationID = try? kameleoonClient.triggerExperiment(visitorCode, 75253) ?? 0
}
else {
// The SDK is not ready, so the user is "out of the experiments". This is the same as if he was bucketed into the reference
variationID = 0
}

if (variationID == 0)) {
//This is the default / reference number of products to display
recommendedProductsNumber = 5
}
else if (variationID == 148382) {
// We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10
}
else if (variationID == 187791) {
// We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8
}
}
}

We provide two code samples to illustrate the triggering of an experiment. The first one uses the .ready approach. It's a bit simpler.

import kameleoonClient

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillEnterForeground(_ application: UIApplication) {
let kameleoonClient = kameleoonDelegate.kameleoonClient
let visitorCode = "1267576" // usually, this would be the internal ID of the current user
var variationID : Int
var recommendedProductsNumber : Int
kameleoonClient.runWhenReady(1000) { success in
if (success)
{
variationID = try? kameleoonClient.triggerExperiment(visitorCode, 75253) ?? 0
if (variationID == 0)) {
// This is the default / reference number of products to display
recommendedProductsNumber = 5
}
else if (variationID == 148382) {
// We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10
}
else if (variationID == 187791) {
// We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8
}
}
else
{
variationID = 0
recommendedProductsNumber = 5
}
}
}
}

This is a second example with the callback runWhenReady() approach. You need to pass a lambda as a second argument, with signature (Bool) -> Void. The boolean that will be passed indicates if the SDK is ready or if the timeout was reached. Note that here we used a timeout of 1000 milliseconds.

Implementing variation code

var recommendedProductsNumber : Int

if (variationID == 0)) {
// This is the default / reference number of products to display
recommendedProductsNumber = 5
}
else if (variationID == 148382) {
// We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10
}
else if (variationID == 187791) {
// We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8
}

To execute different code paths depending on the variation assigned to the visitor, you will need the list of all the experiment's variation IDs. You can find these variation IDs (as well as the experiment ID) by opening the experiment in the back-office interface. By convention, the reference (original variation) always has an ID equal to 0.

Once you have the IDs of the different variations, you can implement a different action for each variation, and one of the code paths will be executed, based on the associated variationID for the current visitor. Generally, this can be done using a simple if / else or switch mechanism. In our example, we just change the number of recommended products with two different variations.

Get variationID

Tracking conversion

let visitorCode = UUID().uuidString

kameleoonClient.trackConversion(visitorCode : "1267576", goalID : 83023, revenue: 1.0) { success in
if success {
// callback code
}
}

After you are done with triggering an experiment, the next step is usually to start tracking conversions. This is done to measure performance characteristics according to the goals that make sense for your business.

For this purpose, use the trackConversion() method of the SDK as shown in the example. You need to pass the visitorCode and goalID parameters so we can correctly track conversion for this particular user.

Get goalID

Obtaining results

Once your implementation is in place on the mobile app side (experiment triggering, variations handling, and conversion tracking), it is time to launch the experiment on the Kameleoon platform. You do this in the same way as for a front-end test. Basic operations such as starting, pausing and stopping the experiment work exactly in the same way.

After the experiment is launched, first results will be available on our standard results page in the back-office after a duration of 30 minutes. This is because (as is the case with front-end testing) visits are considered over after 30 minutes of inactivity. Inactivity in this context means the absence of calls sent to the Kameleoon back-end servers (such calls are made via triggerExperiment(), trackConversion() or flush() methods).

Getting SDK configuration

Overview

When you update your experiment or feature flag configuration, the SDK can get it in two different ways. The first - polling - consists in retrieving the configuration at regular intervals. The second - streaming - is to retrieve the new configuration immediately.

Polling

This mode of obtaining the configuration is used by default. The SDK will send a request to Cloudflare CDN at regular intervals to retrieve the configuration. If you have not set an interval in the SDK configuration, the configuration in SDK will be refreshed every 60 minutes. It can be configured with actions_configuration_refresh_interval parameter.

Benefits:

  • When intervals are moderately spaced, this way of updating configuration consumes nominal memory and network resources.

Streaming

This mode allows the SDK to automatically take into account the new configuration without delay. When turned on, Kameleoon SDK is notified of any changes to the configuration in real-time, thanks to server-sent events (SSE).

Benefits:

  • Makes it possible to propagate and apply a new configuration in real-time.
  • Reduce network traffic compared to polling at short intervals, as streaming does not require sending periodic requests. It opens the connection once and then keeps it permanently open and ready to receive data.
  • The best option for mobile applications requiring real-time updates, as it minimizes battery drain and data usage.

If you rely on instant data updates (real-time), then streaming is for you. If you wish to activate this mode, please contact us.

Reference

This is a full reference documentation of the Swift SDK.

If this is your first time working with the Swift SDK, we strongly recommend you go over our Getting started tutorial to integrate the SDK and start experimenting in a few minutes.

KameleoonClientFactory

create

let siteCode = "a8st4f59bj"
do {
// read client configiration from a file
let kameleoonClient = KameleoonClientFactory.create(sitecode: siteCode)

// pass client configiration as an argument
let config = try KameleoonClientConfig(clientId: "<CLIENT_ID>",
clientSecret: "<CLIENT_SECRET>"
refreshInteval: 1, // minutes
environment: "development") // optional
let kameleoonClient = KameleoonClientFactory.create(sitecode: siteCode,
config: config)
} catch KameleoonError.credentialsNotFound {
// Credentials are not found in the config file or configuration object
}

The starting point for using the SDK is the initialization step. All interaction with the SDK is done through an object named KameleoonClient, therefore you need to create this object. If you pass config parameter, SDK will use it else try to find configuration file and try to parse it.

Arguments
NameTypeDescription
siteCodeStringCode of the website you want to run experiments on. This unique code id can be found in our platform's back-office. This field is mandatory.
configKameleoonClientConfigConfiguration SDK object which can be used instead of configuration file.

KameleoonClient

isReady

let ready = kameleoonClient.ready

For mobile SDKs, the initialization of the Kameleoon Client is not immediate, as it needs to perform a server call to retrieve the current configuration for all active experiments. It is recommended to check if the SDK is ready by calling this method before triggering an experiment. Alternatively, you could setup error catching around the triggerExperiment() method to look for the KameleoonError.sdkNotReady error, or you could use the runWhenReady() method with a callback as detailed in the next paragraph.

Arguments
NameTypeDescription
Return value
NameTypeDescription
readyBoolBoolean representing the status of the SDK (properly initialized, or not yet ready to be used).

runWhenReady

kameleoonClient.runWhenReady(1000) { success in
if (success)
{
variationID = try? kameleoonClient.triggerExperiment(visitorCode, experimentID) ?? 0
if (variationID == 0)) {
// This is the default / reference number of products to display
recommendedProductsNumber = 5
}
else if (variationID == 148382) {
// We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10
}
else if (variationID == 187791) {
// We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8
}
}
else
{
variationID = 0
recommendedProductsNumber = 5
}
}

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

The lambda given as second argument to this method must have signature (Bool) -> Void. The lambda will be called with argument true once the Kameleoon client is ready, and should contain code triggering an experiment and implementing variations. The lambda will be called with argument false if the specified timeout happens before the client is initialized. Usually this case should implement the "reference" variation, as the user will be "out of the experiment" if a timeout takes place.

Arguments
NameTypeDescription
timeoutIntTimeout (in milliseconds). Two versions of this method exist, with and without this argument. If not provided, it will use the default value of 2000 milliseconds.
callback(Bool) -> VoidCallback object. This field is mandatory. It is a lambda expression that will get a Bool argument representing whether the Kameleoon Client became ready before the timeout was reached.

triggerExperiment

let visitorCode = UUID().uuidString
let experimentID = 75253
var variationId = 0

do {
variationId = try kameleoonClient.triggerExperiment(visitorCode, experimentID)
} catch {
switch error {
case KameleoonError.sdkNotReady:
// Exception indicating that the SDK has not completed its initialization yet.
case KameleoonError.visitorCodeNotValid:
// The provided visitor code is not valid.
case KameleoonError.experimentNotFound:
// 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.notTargeted:
// The user did not trigger the experiment, as the associated targeting segment
// conditions were not fulfilled. He should see the reference variation
case KameleoonError.notAllocated:
// The user triggered the experiment, but got into unallocated traffic.
// Usually, this happens because the user has been associated with excluded traffic
default:
// Any other error
}
}

To trigger an experiment, call the triggerExperiment() method of our SDK.

This method takes visitorCode and experimentID as mandatory arguments to register a variation for a given user. If such a user has never been associated with any variation, the SDK returns a randomly selected variation. In case a user with a given visitorCode is already registered with a variation, it will detect the previously registered variation and return the variationID.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential errors.

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is mandatory.
experimentIDIntID of the experiment you want to expose to a user. This field is mandatory.
Return value
NameTypeDescription
variationIDIntID of the variation that is registered for the given visitorCode. By convention, the reference (original variation) always has an ID equal to 0.
Errors Thrown
TypeDescription
KameleoonError.sdkNotReadyError indicating that the SDK has not completed its initialization yet.
KameleoonError.VisitorCodeNotValidError indicating that the provided visitor code is not valid (empty, or longer than 255 characters).
KameleoonError.notTargetedError indicating that the current user did not trigger the required targeting conditions for this experiment. The targeting conditions are defined via Kameleoon's segment builder.
KameleoonError.notAllocatedError indicating that the current user triggered the experiment (met the targeting conditions), but did not activate it. The most common reason for that is that part of the traffic has been excluded from the experiment and should not be tracked.
KameleoonError.experimentConfigurationNotFoundError indicating that the request experiment ID has not been found in the internal configuration of the SDK. This is usually normal and means that the experiment has not yet been started on Kameleoon's side (but code triggering / implementing variations is already deployed on the mobile app's side).

isFeatureActive

let visitorCode = UUID().uuidString
let featureKey = "new_checkout"
var hasNewCheckout = false

do {
hasNewCheckout = try kameleoonClient.isFeatureActive(visitorCode: visitorCode, featureKey: featureKey)
} catch {
switch error {
case KameleoonError.sdkNotReady:
// Exception indicating that the SDK has not completed its initialization yet.
hasNewCheckout = false
case KameleoonError.visitorCodeNotValid:
// The provided visitor code is not valid. Trigger the old checkout for this visitor.
hasNewCheckout = false
case KameleoonError.featureFlagNotFound:
// The Feature Key is not yet in the configuration file that has been fetched by the SDK. Trigger the old checkout for this visitor.
hasNewCheckout = false
default:
// Any other error
hasNewCheckout = false
}
}

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

Previously named: activateFeature - deprecated since SDK version 3.0.0 and will be removed in a future release

This method takes a visitorCode and featureKey as mandatory arguments to check if the feature flag is active for a given user.

If such a user has never been associated with a feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous FeatureFlag value.

note

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

Arguments
NameTypeDescription
visitorCodeStringThe user's unique identifier. This field is mandatory.
featureKeyStringThe key of the feature you want to expose to a user. This field is mandatory.
Return value
TypeDescription
BoolValue of the feature that is registered for a given visitorCode.
Exceptions Thrown
TypeDescription
KameleoonError.sdkNotReadyException indicating that the SDK has not completed its initialization yet.
KameleoonError.visitorCodeNotValidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).
KameleoonError.featureFlagNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and 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).

getFeatureVariationKey

let visitorCode = UUID().uuidString
let featureKey = "new_checkout"
var variationKey = ""

do {
variationKey = try kameleoonClient.getFeatureVariationKey(visitorCode: visitorCode, 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.visitorCodeNotValid:
// The provided visitor code is not valid. Trigger the old checkout for this visitor.
case KameleoonError.featureFlagNotFound:
// The Feature Key is not yet in the configuration file that has been fetched by the SDK. Trigger the old checkout for this visitor.
default:
// Any other error
}
}

To get a feature variation key, call the getFeatureVariationKey() method of our SDK.

This method takes a visitorCode and featureKey as mandatory arguments to get a variation key for a given user.

If a user has never been associated with a feature flag, the SDK returns a variation key randomly, in accordance with the feature flag rules. If a user with a given visitorCode is already registered with the feature flag, the SDK will detect the previous variation key value. If a user does not match any of the rules, the default value will be returned. (The default value is defined in Kameleoon's feature flag delivery rules.)

note

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

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is mandatory.
featureKeyStringKey of the feature you want to expose to a user. This field is mandatory.
Return value
TypeDescription
StringVariation key of the feature flag that is registered for a given visitorCode.
Exceptions Thrown
TypeDescription
KameleoonError.sdkNotReadyException indicating that the SDK has not completed its initialization yet.
KameleoonError.visitorCodeNotValidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).
KameleoonError.featureFlagNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and 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).

getFeatureVariable

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.visitorCodeNotValid:
// The provided visitor code is not valid. Trigger the old checkout for this visitor.
case KameleoonError.featureFlagNotFound:
// 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.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
}
}
note

Previously named: obtainFeatureVariable - deprecated since SDK version 3.0.0 and will be removed in a future release

To get a feature variable of a variation key associated with a user, call the GetFeatureVariable() method of our SDK.

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

If a user has never been associated with this feature flag, the SDK returns a variable value of the variation key randomly, in accordance with the feature flag rules. If a user with a given visitorCode is already registered with this feature flag, the SDK will detect the variable value for previously associated variation. If the user does not match any of the rules, the default variable will be returned.

note

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

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is mandatory.
featureKeyStringKey of the feature you want to expose to a user. This field is mandatory.
variableKeyStringName of the variable you want to get a value. This field is mandatory.
Return value
TypeDescription
Any?Value of variable of variation that is registered for a given visitorCode for this feature flag. Possible types: Bool, Double, String, Array, Dictionary
Exceptions Thrown
TypeDescription
KameleoonError.sdkNotReadyException indicating that the SDK has not completed its initialization yet.
KameleoonError.featureFlagNotFoundException indicating that the requested feature key has not been found in the internal configuration of the SDK. This is usually normal and 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).
KameleoonError.variableNotFoundException indicating that the requested variable has not been found. Check that the variable's key matches the one in your code.
KameleoonError.visitorCodeNotValidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

getVariationAssociatedData

let visitorCode = UUID().uuidString
let experimentID = 75253

do {
let variationID = kameleoonClient.triggerExperiment(visitorCode, experimentID: experimentID)
let jsonObject = kameleoonClient.getVariationAssociatedData(variationID)
let firstName = jsonObject["firstName"] as? String
}
catch {
if let kameleoonError = error as? KameleoonError {
switch kameleoonError {
// Handle error
}
}
}
note

Previously named: obtainVariationAssociatedData - deprecated since SDK version 3.0.0 and will be removed in a future release

To retrieve JSON data associated with a variation, call the getVariationAssociatedData() method of our SDK. The JSON data usually represents some metadata of the variation, and can be configured on our web application interface or via our Automation API.

This method takes the variationID as a parameter and will return the data as a JSON object. It will throw an error (KameleoonError.variationConfigurationNotFound) if the variation ID is wrong or corresponds to an experiment that is not yet online.

Arguments
NameTypeDescription
variationIDIntID of the variation you want to obtain associated data for. This field is mandatory.
Return value
TypeDescription
org.json.JSONObjectData associated with this variationID.
Errors Thrown
TypeDescription
KameleoonError.variationConfigurationNotFoundError indicating that the requested variation 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.

getFeatureAllVariables

let featureKey = "myFeature"
let variationKey = "on"

do {
allVariables = try kameleoonClient.getFeatureAllVariables(featureKey: featureKey, variationKey: variationKey);
} catch KameleoonError.featureFlagNotFound {
// The feature is not yet activated on Kameleoon's side
} catch {
// This is generic Exception handler which will handle all exceptions.
}
note

Previously named: obtainFeatureAllVariables - deprecated since SDK version 3.0.0 and will be removed in a future release

To retrieve the all feature variables, call the getFeatureAllVariables() method of our SDK. A feature variable can be changed easily via our web application.

This method takes one input parameter: featureKey. It will return the data with the [String: Any] type, as defined on the web interface. It will throw an exception (KameleoonError.featureFlagNotFound) if the requested feature has not been found in the internal configuration of the SDK.

Arguments
NameTypeDescription
featureKeyStringIdentification key of the feature you need to obtain. This field is mandatory.
variationKeyStringThe key of the variation you want to obtain. This field is mandatory.
Return value
TypeDescription
[String: Any]Data associated with this feature flag. The values of can be a Int, String, Bool or Dictionary (depending on the type defined on the web interface).
Exceptions Thrown
TypeDescription
KameleoonError.featureFlagNotFoundException indicating that the requested feature 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.
KameleoonError.variationNoFoundException 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.

trackConversion

let visitorCode = UUUID().uuidString
let goalID = 83023

kameleoonClient.addData(visitorCode : visitorCode, data : Interest(2))
kameleoonClient.addData(visitorCode : visitorCode, data : Conversion(goalID : 32, revenue : 10.0, negative : false))
kameleoonClient.trackConversion(visitorCode : visitorCode, goalID : goalID, revenue: 10.0)

To track conversion, use the trackConversion() method. This method requires visitorCode and goalID to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The visitorCode should be identical to the one that was used when triggering the experiment.

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

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is mandatory.
goalIDIntID of the goal. This field is mandatory.
revenueFloatRevenue of the conversion. This field is optional.
Errors Thrown
TypeDescription
KameleoonError.sdkNotReadyError indicating that the SDK has not completed its initialization yet.
KameleoonError.VisitorCodeNotValidError indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

addData

kameleoonClient.addData(visitorCode : visitorCode, data : Interest(2))
kameleoonClient.addData(visitorCode : visitorCode, data : Conversion(goalID : 32, revenue : 10.0, negative : false))

To associate various data with the current user, we can use the addData() method. This method requires the visitorCode as a first parameter, and then accept several additional parameters. Those additional parameters represent the various Data Types allowed in Kameleoon.

Note that the addData() method doesn't return any value and doesn't interact with the Kameleoon back-end servers by itself. Instead, every data declared is saved for further sending via the flush() method described in the next paragraph. This allows a minimal number of server calls to be made, as data are usually regrouped in a single server call triggered by the execution of flush().

note

The triggerExperiment() and trackConversion() methods also sends out previously associated data, exactly as the flush() method.

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is mandatory.
dataDataone or more values conforming to the Data protocol which may be passed separated by a comma.
Errors Thrown
TypeDescription
KameleoonError.sdkNotReadyError indicating that the SDK has not completed its initialization yet.
KameleoonError.VisitorCodeNotValidError indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

flush

let visitorCode = UUID().uuidString

kameleoonClient.addData(visitorCode : visitorCode, data : Interest(2))
kameleoonClient.addData(visitorCode : visitorCode, data : Conversion(goalID : 32, revenue : 10.0, negative : false))
kameleoonClient.flush(visitorCode : visitorCode)

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 automatically by the triggerExperiment() or trackConversion() methods, or manually by 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 be a waste of ressources to send data to the server after each addData() invocation. Just 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
visitorCodeStringUnique identifier of the user. This field is mandatory.
completionHandlerOptional<(Bool) -> Void)>Callback object. This field is an 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.
KameleoonError.VisitorCodeNotValidError indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

getExperimentList

let allExperimentList = kameleoonClient.getExperimentList()

let activeExperimentsForVisitor = kameleoonClient.getExperimentList(visitorCode: visitorCode) //onlyAllocated == true

let allExperimentsForVisitor = kameleoonClient.getExperimentList(visitorCode: visitorCode, onlyAllocated: false)

Returns a list of experiment IDs currently available for the SDK or a list of experiment IDs currently available for specific visitorCode according to the onlyAllocated option.

This method can takes two input parameters: visitorCode and onlyAllocated. If onlyAllocated parameter is true result contains only active experiments, otherwise it contains all targeted experiments for specific visitorCode.

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is optional.
onlyAllocatedBoolThe value is true by default, result contains only active for the visitor experiments. Set false for fetching all targeted experiment IDs. This field is optional.
Return value
TypeDescription
[Int]List of all experiment's IDs or a list of experiment IDs available for specific visitorCode according to the onlyActive option.

getFeatureList

let allFeatureList = kameleoonClient.getFeatureList()

The get a list of feature flag keys currently available for the SDK, call the getFeatureList() method.

Return value
TypeDescription
[String]List of feature flag keys

getActiveFeatureListForVisitor

let activeFeatureFlags = kameleoonClient.getFeatureList(visitorCode: visitorCode)

This method takes one input parameter: visitorCode and will return a list of feature flag keys currently available and active for specific visitorCode.

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is optional.
onlyActiveBoolThe value is true by default, result contains only active for the user feature flags. Set false for fetching all targeted feature flag IDs. This field is optional.
Return value
TypeDescription
[String]List of feature flag keys which are active for a specific visitorCode

getRemoteData

struct Test1: Decodable {
let value: String

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

do {
try kameleoonClient.getRemoteData(key: "test") { (test: Test1) in
print(test.value)
}
} catch {
}

do {
try kameleoonClient.getRemoteData(key: "test") { (data: Data) in
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
}
} catch {
}

The getRemoteData method allows you to retrieve data (according to a key passed as argument) for specified siteCode (specified in KameleoonClientFactory.create) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.

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

Arguments
NameTypeDescription
keyStringThe key that the data you try to get is associated with. This field is mandatory.
completionHandlerOptional<(T) -> Void)> where T: DecodableGeneric callback object. It is a lambda expression that will asynchronously get called with a T argument (must implement Decodable protocol). Data can be used as default type. This field is mandatory.
Errors Thrown
TypeDescription
Network Connection ErrorError indicating that the SDK isn't available to make network request to a server.
JSON Parser ErrorError indicating that the retrieved data is not available for JSON parsing

updateConfigurationHandler

kameleoonClient.updateConfigurationHandler {
// configuration was updated
}

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.

Arguments
NameTypeDescription
handlerOptional<() -> Void)>The handler that will be called when the configuration is updated using a real-time configuration event.

Data

Conversion

try? kameleoonClient.addData(visitorCode: visitorCode,
data: Conversion(goalID: 32,
revenue: 10.0,
negative: false))
NameTypeDescription
goalIDStringID of the goal. This field is mandatory.
revenueFloatConversion revenue. This field is optional.
negativeBoolDefines if the revenue is positive or negative. This field is optional.

CustomData

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

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

try? kameleoonClient.addData(visitorCode: visitorCode,
data: CustomData(id: 1, values: ["first value", "second value"]))
NameTypeDescription
indexIntIndex / ID of the custom data to be stored. This field is mandatory.
valueStringValue of the custom data to be stored. This field is mandatory.
valuesString... or [String]Value(s) of the custom data to be stored.
note

The index (ID) of the custom data is available on our Back-Office, in the Custom data configuration page. Be careful: this index starts at 0, so the first custom data you create for a given site would have the ID 0, not 1.

Device

try? kameleoonClient.addData(visitorCode: visitorCode,
data: Device.desktop);
NameTypeDescription
deviceDeviceList of devices: phone, tablet, desktop. This field is mandatory.