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
.
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: 3.0.6 (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.
- CocoaPods
- 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
With Swift Package Manager, add a package dependency to your Xcode project. 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:
dependencies: [
.package(url: "https://github.com/Kameleoon/client-swift.git", from("3.0.3"))
]
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:
<?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>actions_configuration_refresh_interval</key>
<integer>60</integer>
</dict>
</plist>
Here are the currently available keys you can set:
actions_configuration_refresh_interval
(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 interval. Once you launch an experiment, pause the experiment, or stop the experiment, it may take up to the number of minutes that you specify as the refresh interval to propagate the change to all users' Android devices. If not specified, the default interval is 60 minutes.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 optionsproduction
,staging
,development
. If not specified, the default value isproduction
. 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 siteCode = "a8st4f59bj"
do {
// pass client configuration as an argument
let config = try KameleoonClientConfig(environment: "development",
refreshIntervalMinutes: 15)
let kameleoonClient = try KameleoonClientFactory.create(sitecode: siteCode,
config: config)
} catch {
// Unexpected error occurred
}
do {
// read client configuration from a file 'kameleoon-client-swift.plist'
let kameleoonClient = try KameleoonClientFactory.create(sitecode: siteCode)
} 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 Android SDK. After the client fetches the first configuration of experiments, 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.
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 can be left out of the experiment when 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
Name | Type | Description |
---|---|---|
siteCode | String | Site code of the website you want to run experiments on. You can find this unique ID in the Kameleoon app. This field is required. |
config | KameleoonClientConfig | Configuration SDK object to use instead of the .pfile configuration file. |
Return value
Name | Type | Description |
---|---|---|
kameleoonClient | KameleoonClient | Instance of KameleoonClient |
Example code
let siteCode = "a8st4f59bj"
do {
// pass client configuration as an argument
let config = try KameleoonClientConfig(refreshInteval: 10, // in minutes, optional
environment: "development") // optional
let kameleoonClient = try KameleoonClientFactory.create(sitecode: siteCode,
config: config)
} catch {
// Unexpected error occurred
}
do {
// read client configuration from a file 'kameleoon-client-swift.plist'
let kameleoonClient = KameleoonClientFactory.create(sitecode: siteCode)
} 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 set up error catching around the triggerExperiment()
method to look for the KameleoonError.sdkNotReady
error, or you can use the runWhenReady()
method with a callback.
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). |
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 teh 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
Name | Type | Description |
---|---|---|
timeout | Int | Timeout (in milliseconds). This field is optional. If not provided, it will use the default value of 2000 milliseconds. |
callback | (Bool) -> Void | Callback 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)
{
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
}
}
triggerExperiment()
The triggerExperiment()
method will be deprecated as part of sunsetting the SDK/Hybrid experimentation in September 2023. Use feature experimentation methods instead.
To trigger an experiment, call the triggerExperiment()
method of our SDK.
This method takes a visitorCode
and an experimentID
as required arguments and returns the variation to use for the specified user. If the user has not been assigned to a variation previously, this method returns a randomly-selected variationID
. If the visitorCode
is already registered to a variation, this method returns the previously assigned variationID
.
Make sure your code uses proper error handling to catch potential exceptions (as shown in the example code below).
Arguments
Name | Type | Description |
---|---|---|
visitorCode | String | Unique identifier of the user in your app. This field is required. |
experimentID | Int | ID of the experiment you want to expose to a user. This field is required. |
Return value
Name | Type | Description |
---|---|---|
variationID | Int | ID of the variation that is registered for the given visitorCode . By convention, the reference (original variation) always has an ID of 0 . |
Errors thrown
Type | Description | |
---|---|---|
KameleoonError.sdkNotReady | Error indicating that the SDK has not completed initialization yet. | |
KameleoonError.VisitorCodeNotValid | Error indicating that the provided visitor code is not valid (it is either empty or longer than 255 characters). | |
KameleoonError.notTargeted | Error 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.notAllocated | Error indicating that the current user triggered the experiment (met the targeting conditions), but did not activate it. The most common reason for this error is that part of the traffic has been excluded from the experiment and should not be tracked. | |
KameleoonError.experimentConfigurationNotFound | Error indicating that the request experiment ID was not found in the internal configuration of the SDK. This usually means that the experiment has not started on Kameleoon's side but code that triggers or implements variations is already deployed on the mobile app's side. |
Example code
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
}
}
isFeatureActive()
This method was previously named activateFeature
, which was deprecated in SDK version 3.0.0
and will be removed in a future release.
To activate a feature toggle, call this method. This method accepts a visitorCode
and featureKey
as required arguments to check if the specified feature will be active for a given user.
If the visitorCode
for the user 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 a user with the specified visitorCode
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
Name | Type | Description |
---|---|---|
visitorCode | String | The user's unique identifier. This field is required. |
featureKey | String | The key of the feature you want to expose to a user. This field is required. |
Return value
Type | Description |
---|---|
Bool | Value of the feature that is registered for a given visitorCode . |
Exceptions thrown
Type | Description |
---|---|
KameleoonError.sdkNotReady | Exception indicating that the SDK is not fully initialized yet. |
KameleoonError.visitorCodeNotValid | Exception indicating that the provided visitor code is not valid (it is either empty or longer than 255 characters). |
KameleoonError.featureFlagNotFound | Exception 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 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
}
getFeatureVariationKey()
Use this method to get the feature variation key for a specific user. This method takes a visitorCode
and featureKey
as required arguments to retrieve the variation key for the specified user.
If the visitorCode
for the user has never been associated with this feature flag, the SDK returns a randomly assigned variation key (according to the feature flag rules). If the user with the specified visitorCode
is already registered with this feature flag, this method returns the previous variation key. If the user 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
Name | Type | Description |
---|---|---|
visitorCode | String | Unique identifier for the user. This field is required. |
featureKey | String | Key of the feature you want to expose to a user. This field is required. |
Return value
Type | Description |
---|---|
String | Variation key of the feature flag that is registered for a given visitorCode . |
Exceptions thrown
Type | Description |
---|---|
KameleoonError.sdkNotReady | Exception indicating that the SDK has not completed its initialization yet. |
KameleoonError.visitorCodeNotValid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
KameleoonError.featureFlagNotFound | Exception 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). |
Example code
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
}
}
getFeatureVariable()
This method was previously named obtainFeatureVariable()
, which was deprecated in SDK release 3.0.0 and will be removed in a future release.
Call this method to get the feature variable of a variation key associated with a user.
This method takes visitorCode
, featureKey
, and variableKey
as required arguments to get the variable of the variation key for a given user.
If a user has never been associated with this feature flag, the SDK returns a randomly assigned variable value of the variation key, in accordance with the feature flag rules. If a user with the specified visitorCode
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.
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.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
}
}
getVariationAssociatedData()
The GetVariationAssociatedData()
method will be deprecated as SDK and Hybrid type experiments are being merged with feature experimentation in September 2023. Use feature experimentation methods instead.
This method was previously named obtainVariationAssociatedData
. It was deprecated in SDK version 3.0.0
and will be removed in a future release.
Call this method to retrieve any JSON data associated with a variation. The JSON data usually represents metadata that you have assigned to the variation, and can be configured in the Kameleoon app or using the Automation API.
This method accepts the variationID
as an argument and returns the JSON data as a JSON object. It will throw an error (KameleoonError.variationConfigurationNotFound
) if the variationID
does not exist or corresponds to an experiment that is not yet online.
Arguments
Name | Type | Description |
---|---|---|
variationID | Int | ID of the variation you want to get associated data for. This field is required. |
Return value
Type | Description |
---|---|
org.json.JSONObject | Data associated with this variationID . |
Errors thrown
Type | Description |
---|---|
KameleoonError.variationConfigurationNotFound | Error indicating that the requested variation ID has not been found in the internal configuration of the SDK. This usually means that the variation's corresponding experiment has not yet been activated on Kameleoon's side. |
Example code
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
}
}
}
getFeatureAllVariables()
This method was previously named: obtainFeatureAllVariables
, which was deprecated in SDK version 3.0.0
and will be removed in a future 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.featureFlagNotFound
) if the requested feature has not been found in the internal configuration of the SDK.
Arguments
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). |
Exceptions thrown
Type | Description |
---|---|
KameleoonError.featureFlagNotFound | Exception 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.variationNoFound | Exception 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.getFeatureAllVariables(featureKey: featureKey, variationKey: variationKey);
} catch KameleoonError.featureFlagNotFound {
// The feature is not yet activated on Kameleoon's side
} catch {
// This is a generic Exception handler that will handle all exceptions.
}
trackConversion()
Use this method to track conversions. 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 your app used to trigger the experiment.
The trackConversion()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | String | Unique identifier of the user. This field is required. |
goalID | Int | ID of the goal. This field is required. |
revenue | Float | Revenue of the conversion. This field is optional. |
Errors thrown
Type | Description |
---|---|
KameleoonError.sdkNotReady | Error indicating that the SDK has not completed its initialization yet. |
KameleoonError.VisitorCodeNotValid | Error indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
Example code
let visitorCode = UUID().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)
addData()
To associate data with the current user, we can use the addData()
method. This method requires the visitorCode
as a first argument, and then accepts several additional arguments. Those additional arguments 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, all added data is saved until you call the flush()
method as described in the next section. This allows a minimal number of server calls to be made, as all data entries are grouped into a single server call that are triggered when you execute flush()
.
The triggerExperiment()
and trackConversion()
methods also send out all previously associated data, exactly as though the flush()
method were called.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | String | Unique identifier of the user. This field is required. |
data | Data | One or more values conforming to the Data protocol which you pass separated by a comma. |
Errors thrown
Type | Description |
---|---|
KameleoonError.sdkNotReady | Error indicating that the SDK is not fully initialized yet. |
KameleoonError.VisitorCodeNotValid | Error indicating that the provided visitorCode is not valid (it is either empty or longer than 255 characters). |
Example code
kameleoonClient.addData(visitorCode : visitorCode, data : Interest(2))
kameleoonClient.addData(visitorCode : visitorCode, data : Conversion(goalID : 32, revenue : 10.0, negative : false))
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 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 waste of resources to send data to the server after each addData()
invocation when you can 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
Name | Type | Description |
---|---|---|
visitorCode | String | Unique identifier of the user. This field is required. |
completionHandler | Optional<(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
Type | Description |
---|---|
KameleoonError.sdkNotReady | Error indicating that the SDK has not completed its initialization yet. |
KameleoonError.VisitorCodeNotValid | Error indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
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)
getExperimentList()
The getExperimentList()
method will be deprecated as SDK and Hybrid type experiments are being merged with feature experimentation in September 2023. Use feature experimentation methods instead.
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 takes two input arguments: visitorCode
and onlyAllocated
. If the onlyAllocated
argument is true
, the result contains only active experiments, otherwise it contains all targeted experiments for the specified visitorCode
.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | String | Unique identifier of the user. This field is optional. |
onlyAllocated | Bool | The value is true by default. The result contains only active for the visitor experiments. Set false for fetching all targeted experiment IDs. This field is optional. |
Return value
Type | Description |
---|---|
[Int] | List of all experiment's IDs or a list of experiment IDs available for specific visitorCode according to the onlyActive option. |
Example code
let allExperimentList = kameleoonClient.getExperimentList()
let activeExperimentsForVisitor = kameleoonClient.getExperimentList(visitorCode: visitorCode) //onlyAllocated == true
let allExperimentsForVisitor = kameleoonClient.getExperimentList(visitorCode: visitorCode, onlyAllocated: false)
getFeatureList()
To get the list of feature flag keys that are currently available to the SDK, call this method.
Return value
Type | Description |
---|---|
[String] | List of feature flag keys |
Example code
let allFeatureList = kameleoonClient.getFeatureList()
getActiveFeatureListForVisitor()
This method takes one argument, visitorCode
and returns a list of feature flag keys currently available and active for the specified visitorCode
.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | String | Unique identifier of the user. This field is optional. |
onlyActive | Bool | The value is true by default. The result contains only active for the user feature flags. Set false for fetching all targeted feature flag IDs. This field is optional. |
Example code
let activeFeatureFlags = kameleoonClient.getFeatureList(visitorCode: visitorCode)
Return value
Type | Description |
---|---|
[String] | List of feature flag keys which are active for a specific visitorCode |
getRemoteData()
The getRemoteData
method retrieves data (for the specified key
argument) for your siteCode
(specified in KameleoonClientFactory.create
) from a remote Kameleoon server. Remote data is usually stored on our remote servers using the Data API. This method, along with our highly scalable servers, provides a convenient way to quickly store additional data that you can later retrieve for each of your visitors.
Note that since a server call is required, this mechanism is asynchronous, and you must pass a completionHandler
as an argument to the method.
Arguments
Name | Type | Description |
---|---|---|
key | String | The key that the data you try to get is associated with. This field is required. |
completionHandler | Optional<(T) -> Void)> where T: Decodable | Generic 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. |
Errors thrown
Type | Description |
---|---|
Network Connection Error | Error indicating that the SDK isn't available to make network requests to a server. |
JSON Parser Error | Error indicating that the retrieved JSON data could not be parsed. |
Example code
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 {
}
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
Name | Type | Description |
---|---|---|
handler | Optional<() -> 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.
Name | Type | Description |
---|---|---|
goalID | String | ID of the goal. This field is required. |
revenue | Float | Conversion revenue. This field is optional. |
negative | Bool | Defines if the revenue is positive or negative. This field is optional. |
Example code
try? kameleoonClient.addData(visitorCode: visitorCode,
data: 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.
Name | Type | Description |
---|---|---|
index | Int | The index a (a unique ID) of the custom data to store. This field is required. |
value | String | Value of the custom data to store. This field is required. |
values | String... or [String] | Value(s) of the custom data to store. |
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(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"]))
Device
Store information about the user's device.
Name | Type | Description |
---|---|---|
device | Device | List of devices: phone , tablet , desktop . This field is required. |
Example code
try? kameleoonClient.addData(visitorCode: visitorCode,
data: Device.desktop);