Con el SDK de iOS (Swift) de Kameleoon, puede ejecutar experimentos y activar feature flags en aplicaciones móviles nativas de iOS. Integrar el SDK en aplicaciones Swift es sencillo y su huella (memoria y uso de red) es baja.
Primeros pasos: Para obtener ayuda para comenzar, consulte la guía del desarrollador.
Changelog: Última versión del SDK de Swift: 4.25.0 Changelog.
Métodos del SDK: Para la documentación de referencia completa de los métodos del SDK de iOS, consulte la sección referencia.
Guía del desarrollador
Follow these steps to install and configure the Kameleoon iOS SDK in your application for the first time.
Primeros pasos
Kit de inicio
Para facilitarle el comienzo, Kameleoon proporciona un kit de inicio y una aplicación de demostración para probar el SDK. El kit de inicio incluye una aplicación totalmente configurada con ejemplos que muestran cómo se pueden utilizar los métodos del SDK en una aplicación. El kit de inicio, la aplicación de demostración y las instrucciones detalladas están disponibles en Starter kit for iOS
Prerequisites
- Use Swift version 5.0 or higher on the iOS platform. Support for earlier iOS applications (including earlier Swift versions and Objective-C apps) is not planned. A Universal Framework version is available, compatible both with x86_64 (for the iOS Simulator) and ARM (for production deployment into the App Store).
Instalación
Puede instalar el SDK de iOS utilizando CocoaPods o 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: 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"))
]
Configuración adicional
To customize the SDK’s behavior, create a kameleoon-client-swift.plist configuration file in the root directory of your Xcode project. You can also download a sample configuration file.
Estas son las claves que puede establecer:
| Key | Description | Default value |
|---|
refreshIntervalMinute / refresh_interval_minute (opcional) | Specifies the refresh interval, in minutes, for the SDK to fetch the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments. If left unspecified, the default interval is 60 minutes. Additionally, a streaming mode is available that uses server-sent events (SSE) to push new configurations to the SDK automatically and apply them in real-time. | 60 minutos |
dataExpirationIntervalMinute / data_expiration_interval_minute (opcional) | Designates the predefined time period, in minutes, that the SDK stores the visitor and their associated data. Each data instance is evaluated individually, allowing you to set the amount of time the SDK saves data before automatically deleting it. If no interval is specified, the SDK does not automatically delete data from the device. | Date.distantFuture |
defaultTimeoutMillisecond / default_timeout_millisecond (opcional) | Specifies the time interval, in milliseconds, that it takes for network requests from the SDK to time out. Set the value to 30000 milliseconds (30 seconds) or more if you do not have a stable connection. Some methods have additional parameters for method-specific timeouts, but if you do not specify them explicitly, el valor predeterminado es used. | 10000 ms |
trackingIntervalMillisecond / tracking_interval_millisecond (opcional) | Specifies the interval for tracking requests, in milliseconds. All visitors who were evaluated for any feature flag or had data flushed will be included in this tracking request, which is performed once per interval. The minimum value is 1000 ms and the maximum value is 5000 ms. | 1000 ms |
environment / environment (opcional) | For customers using multi-environment experimentation and feature flagging, this option specifies which feature flag configuration to use. De forma predeterminada, each feature flag has the options production, staging, and development. If not specified, el valor predeterminado es production. More information. | nil |
isUniqueIdentifier / is_unique_identifier (opcional) | Indicates that the specified visitorCode is a unique identifier. | false |
networkDomain / network_domain (opcional) | Dominio personalizado utilizado por los SDKs para las solicitudes salientes, a menudo para proxy. Debe ser un dominio válido (por ejemplo, example.com o sub.example.com). Los formatos no válidos se sustituyen por el valor de Kameleoon. | nil |
defaultDataFile / default_datafile (opcional) | The default_datafile feature ensures the Kameleoon SDK is always READY by providing a fallback configuration when no cached data file exists. Developers can preload a valid configuration by fetching it from https://sdk-config.kameleoon.eu/v3/<sitecode> and passing it as default_datafile during initialization. When a dateModified timestamp (in milliseconds) is provided and is newer than the cached version, the SDK will use the default datafile instead of the cached version. If dateModified is omitted, the default datafile is only applied when no cached version exists. This ensures the SDK always has a valid configuration, whether default, cached, or updated. | nil |
activityTrackingIntervalMillisecond / activity_tracking_interval_millisecond (opcional) | Defines the interval at which activity events are sent. Modifying this parameter can have side effects. Check this section before using it. The minimum and el valor predeterminado es 15 000 ms. Setting this value to 0 disables periodic activity tracking; in this case, only a single activity event is sent at application startup. | 15 000 ms |
If you specify a visitorCode and set the isUniqueIdentifier parameter to true, the SDK methods use the visitorCode value as the unique visitor identifier, which is useful for cross-device experimentation. The SDK links the flushed data to the visitor that is associated with the specified identifier.isUniqueIdentifier puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
Using activityTrackingIntervalMillisecond
El parámetro activityTrackingIntervalMillisecond está diseñado para ayudar a reducir el consumo de batería y el uso de red. Sin embargo, cambiar su valor puede tener efectos secundarios significativos que debe considerar cuidadosamente.
Review its impact on the following features:
-
Elapsed time triggers
- If the configured elapsed time is shorter than the tracking interval, the trigger will not fire as expected.
-
Elapsed time segments
- If the elapsed time is shorter than the tracking interval, users may not be included in the segment as intended.
-
Time spent goals
- If the elapsed time is shorter than the tracking interval, the goal may never be reached.
-
Time elapsed since last visit in the results page
- Measurements for “time elapsed since last visit” become less precise when the elapsed time is close to or below the tracking interval.
-
Visits count
- A new visit is created after 30 minutes of inactivity. If the tracking interval is longer than 30 thirty minutes, a new visit will be created at each tracking interval.
Setting activityTrackingIntervalMillisecond to 0 disables periodic activity tracking entirely. In this configuration, only a single activity event is sent at application startup, which renders all of the features listed above unusable.
Initialize the Kameleoon Client
After you’ve set up the SDK in your application, you must create the Kameleoon Client. A Client is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you need to run an experiment.
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
trackingIntervalMillisecond: 500, // optional, 1000 milliseconds by default
environment: "production", // optional
isUniqueIdentifier: false, // optional, false by default. Set to true if the visitorCode corresponds to your customer's unique userId.
networkDomain: "example.com", // optional, nil by default
defaultDataFile: "{...}", // optional, nil by default
activityTrackingIntervalMillisecond: 20_000 // optional, 15_000 milliseconds by default
)
let kameleoonClient = try KameleoonClientFactory.create(
siteCode: siteCode,
visitorCode: visitorCode, // optional
config: config // optional
)
} catch KameleoonError.visitorCodeInvalid {
// Provided visitor code is invalid
} catch KameleoonError.siteCodeIsEmpty {
// Indicates that provided site code is empty
} catch {
// Unexpected error occurred
}
do {
// read client configuration from a file 'kameleoon-client-swift.plist'
// visitor code isn't provided, so SDK generates a random visitor code which it will use in the future
let kameleoonClient = try KameleoonClientFactory.create(siteCode: siteCode)
} catch KameleoonError.visitorCodeInvalid {
// Provided visitor code is invalid
} catch {
// Unexpected error occurred
}
The KameleoonClientFactory.create() method initializes the client, but the client is not immediately ready for use. The client must retrieve the current configuration of experiments and feature flags (along with their traffic repartition) from a Kameleoon remote server. This retrieval requires the client to have network access, which is not always available. Until the Kameleoon Client is fully ready, you should not attempt to run other methods in the Kameleoon iOS SDK. After the client fetches the first configuration of feature flags, it periodically refreshes the configuration. If the refresh fails for any reason, the Kameleoon client continues to function using the previous configuration.
Puede utilizar el getter público .ready para comprobar si la inicialización del cliente Kameleoon ha finalizado.
Alternatively, a helper callback can encapsulate the logic of experiment triggering and variation implementation. The best approach (.ready or callback) depends on preferences and the use case. Using .ready is recommended when the SDK is expected to be ready for use soon. Por ejemplo, .ready is appropriate when running an experiment on a dialog that would be accessible only after a few seconds or minutes of navigation within the app. A callback is recommended when there is a high probability that the SDK will still be initializing when the experiment is reached. Por ejemplo, an experiment visible at the launch of the app should use a callback that makes the application wait until either the SDK is ready or a specified timeout has expired.
It’s your responsibility as the app developer to ensure the client is ready before calling any methods. A good practice is to always assume that the app user should be left out of the experiment if the Kameleoon client is not yet ready. This exclusion is easy to do, as it corresponds to the implementation of the default reference variation logic as shown in the code sample above.
You’re now ready to implement feature management and features flags. See the Reference section for details about additional methods.
Best practices for initialization and usage
- Initializing
KameleoonClient as a singleton as early as possible after the application starts is recommended, as initialization may take some time. Since initialization is asynchronous, it does not block or delay the application startup process.
- Before using
KameleoonClient, verify that it is initialized by calling the runWhenReady method. Otherwise, attempts to use the client before it is ready will result in errors.
- ⚠️ Most key methods may throw errors, so proper exception handling is required. Be sure to review the documentation for each method you use to understand its potential errors.
// Initialize `KameleoonClient` on application startup and use it as a singleton later
do {
let kameleoonClient = try KameleoonClientFactory.create(siteCode: "<siteCode>");
} catch {}
// Example: Apply a discount percentage based on an feature flag variable's value
func applyDiscountIfApplicable() {
client.runWhenReady(timeoutMilliseconds: 1000) { ready in
guard ready else { return }
if let variation = try? client.getVariation(featureKey: "discount"),
let discount = variation.variables["discount_value"]?.value as? Double {
applyDiscount(value: discount)
}
}
}
// Initialize `KameleoonClient` on application startup and use it as a singleton later
do {
let kameleoonClient = try KameleoonClientFactory.create(siteCode: "<siteCode>");
} catch {}
// Example: Apply a discount percentage based on an feature flag variable's value
func applyDiscountIfApplicable() async throws {
try await client.runWhenReady(timeoutMilliseconds: 1000)
if let variation = try client.getVariation(featureKey: "discount"),
let discount = variation.variables["discount_value"]?.value as? Double {
applyDiscount(value: discount)
}
}
Activación de un feature flag
Recuperación de la configuración de un flag
Para implementar un feature flag en su código, primero debe crear el feature flag en su cuenta de Kameleoon.
Para determinar el estado o la variación de un feature flag para un usuario específico, debe utilizar el método getVariation() o isFeatureActive() para recuperar la configuración basada en el featureKey.
El método getVariation() gestiona tanto los feature flags simples con estados ON/OFF como los flags más complejos con múltiples variaciones. El método recupera la variación adecuada para el usuario comprobando las reglas de la funcionalidad, asignando la variación y devolviéndola en función del featureKey y el visitorCode.
El método isFeatureActive() puede utilizarse si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON u OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación.
Si su feature flag tiene variables asociadas (como comportamientos específicos vinculados a cada variación), getVariation() también le permite acceder al objeto Variation, que proporciona detalles sobre la variación asignada y su experimento asociado. Este método comprueba si el usuario está segmentado, encuentra la variación asignada al visitante y la guarda en almacenamiento. Cuando track=true, el SDK enviará el evento de exposición al experimento especificado en la siguiente solicitud de seguimiento, que se desencadena automáticamente según el tracking_interval_millisecond del SDK. De forma predeterminada, este intervalo está configurado en 1000 milisegundos (1 segundo).
El método getVariation() le permite controlar si se realiza el seguimiento. Si track=false, el SDK no enviará eventos de exposición. Esto es útil si prefiere no realizar el seguimiento de los datos a través del SDK y, en su lugar, basarse en el seguimiento del lado del cliente gestionado por el motor de Kameleoon, por ejemplo. Además, establecer track=false resulta útil cuando se utiliza el método getVariations(), donde puede que solo necesite las variaciones de todos los flags sin desencadenar eventos de seguimiento. Si desea saber más sobre cómo funciona el seguimiento, consulte este artículo
Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes
Para segmentar a un usuario, asegúrese de haber añadido los puntos de datos relevantes a su perfil antes de recuperar la variación de la funcionalidad o comprobar si el flag está activo. Utilice el método addData() para añadir estos puntos de datos al perfil del usuario.
To retrieve data points collected on other devices, use the getRemoteVisitorData() method. This method asynchronously fetches data from the servers. It is important to call getRemoteVisitorData() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.
Para obtener más información sobre las condiciones de segmentación disponibles, consulte el artículo detallado sobre este tema.
Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device. See the complete list here.
Si necesita realizar el seguimiento de puntos de datos adicionales más allá de los que se recopilan automáticamente, puede utilizar la funcionalidad de Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método flush() para enviar los datos recopilados a los servidores de Kameleoon para su análisis.
Seguimiento de conversiones de objetivos
Cuando un usuario completa una acción deseada (como realizar una compra), se registra como una conversión. Para hacer seguimiento de las conversiones, utilice el método trackConversion() y proporcione el parámetro requerido goalId.
La solicitud de seguimiento de conversiones se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos por tracking_interval_millisecond). Si prefiere enviar la solicitud de inmediato, utilice el método flush() con el parámetro instant=true.
Experimentación entre dispositivos
Para dar soporte a los visitantes que acceden a una aplicación desde varios dispositivos, Kameleoon permite sincronizar los datos del visitante previamente recopilados entre cada uno de sus dispositivos y reconciliar su historial de visitas entre dispositivos mediante la experimentación entre dispositivos. Los casos de estudio y la información detallada sobre cómo Kameleoon gestiona los datos entre dispositivos están disponibles en el artículo sobre experimentación entre dispositivos.
Sincronización de datos personalizados entre dispositivos
Aunque la sincronización de mapeo personalizado se utiliza para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización de mapeo personalizado:
Mismo ID de usuario en todos los dispositivos
Si el mismo ID de usuario se utiliza de forma consistente en todos los dispositivos, la sincronización se gestiona automáticamente sin necesidad de una sincronización de mapeo personalizado. Basta con llamar al método getRemoteVisitorData() cuando desee sincronizar los datos recopilados entre varios dispositivos.
Instancias multi-servidor con IDs consistentes
En configuraciones complejas que involucran varios servidores (por ejemplo, instancias de servidor distribuidas), donde el mismo ID de usuario está disponible en todos los servidores, la sincronización entre servidores (con getRemoteVisitorData()) es suficiente sin necesidad de una sincronización adicional de mapeo personalizado.
Los clientes que necesiten datos adicionales pueden consultar la descripción del método getRemoteVisitorData() para obtener más orientación. En el código siguiente se asume que el mismo identificador único (en este caso, el visitorCode, que también puede denominarse userId) se utiliza de manera consistente entre los dos dispositivos para una recuperación precisa de los datos.
Si desea sincronizar los datos recopilados en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
// In this example, Custom data with index `90` was set to "Visitor" scope in Kameleoon.
let visitorScopeCustomDataIndex = 90
kameleoonClient.addData(CustomData(id: visitorScopeCustomDataIndex, values: "your data"))
kameleoonClient.flush()
// Before working with the data, call `getRemoteVisitorData`.
kameleoonClient.getRemoteVisitorData { result in
// After calling, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
// So, "your data" will be available to target and track the visitor.
}
// In this example, Custom data with index `90` was set to "Visitor" scope in Kameleoon.
let visitorScopeCustomDataIndex = 90
kameleoonClient.addData(CustomData(id: visitorScopeCustomDataIndex, values: "your data"))
kameleoonClient.flush()
// Before working with the data, call `getRemoteVisitorData`.
try await kameleoonClient.getRemoteVisitorData()
// After calling, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
// So, "your data" will be available to target and track the visitor.
Uso de datos personalizados para la fusión de sesiones
La experimentación entre dispositivos permite combinar el historial de un visitante en cada uno de sus dispositivos (reconciliación de historial). La reconciliación de historial permite fusionar diferentes sesiones de un visitante en una sola. Para reconciliar el historial de visitas, utilice CustomData para proporcionar un identificador único del visitante. Para más información, consulte la documentación dedicada.
Una vez habilitada la reconciliación entre dispositivos, al llamar a getRemoteVisitorData() con el parámetro userId se recuperan todos los datos conocidos para un usuario determinado.
Las sesiones con el mismo identificador siempre verán la misma variación en un experimento. En la vista Visitor de las páginas de resultados de su experimento, estas sesiones aparecerán como un único visitante.
La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, existen algunas limitaciones en cuanto a la asignación de variaciones entre dispositivos. Estas limitaciones se describen aquí.
Siga la guía de activación de la reconciliación de historial entre dispositivos para configurar sus datos personalizados en la plataforma Kameleoon.
Posteriormente, puede usar el SDK de forma normal. Los siguientes métodos pueden ser útiles en el contexto de la fusión de sesiones:
getRemoteVisitorData() with passed isUniqueIdentifier=true to KameleoonClientConfig - to retrieve data for all linked visitors.
trackConversion() or flush() with passed isUniqueIdentifier=true to KameleoonClientConfig - to track some data for specific visitor that is associated with another visitor.
A continuación se muestra un ejemplo de cómo usar datos personalizados para la fusión de sesiones.
// In this example, `91` represents the Custom Data's index,
// configured as a unique identifier in Kameleoon.
let mappingIndex = 91;
let featureKey = "ff123";
// 0. Initializing anonymous KameleoonClient
// Assume `anonymousVisitorCode` is the randomly generated ID for the visitor.
let anonymousKameleoonClient = KameleoonClientFactory.create(
siteCode: siteCode,
visitorCode: anonymousVisitorCode
)
anonymousKameleoonClient.runWhenReady { result in
// ...
}
// 1. Before the visitor is authenticated
// Retrieve the variation for an unauthenticated visitor.
let anonymousVariation = anonymousKameleoonClient.getVariation(featureKey)
// 2. After the visitor is authenticated
// Assume `userId` is the visitor code of the authenticated visitor.
anonymousKameleoonClient.addData(CustomData(id: mappingIndex, values: userId))
anonymousKameleoonClient.flush(instant: true)
KameleoonClient userKameleoonClient = KameleoonClientFactory.create(
siteCode: siteCode,
visitorCode: userId,
config: KameleoonClientConfig(
isUniqueIdentifier: true // Indicate that `userId` is a unique identifier
)
)
userKameleoonClient.runWhenReady { result in
// ...
}
// 3. After the visitor has been authenticated
// Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
let userVariation = userKameleoonClient.getVariation(featureKey: featureKey)
let isSameVariation = userVariation.key == anonymousVariation.key // true
// The `userId` and `anonymousVisitorCode` are now linked and tracked as a single visitor.
userKameleoonClient.trackConversion(goalId: 123, revenue: 10.0);
// Additionally, the linked visitors will share all fetched remote visitor data.
userKameleoonClient.getRemoteVisitorData { result in
// ...
}
// In this example, `91` represents the Custom Data's index,
// configured as a unique identifier in Kameleoon.
let mappingIndex = 91;
let featureKey = "ff123";
// 0. Initializing anonymous KameleoonClient
// Assume `anonymousVisitorCode` is the randomly generated ID for the visitor.
let anonymousKameleoonClient = KameleoonClientFactory.create(
siteCode: siteCode,
visitorCode: anonymousVisitorCode
)
try await anonymousKameleoonClient.runWhenReady()
// 1. Before the visitor is authenticated
// Retrieve the variation for an unauthenticated visitor.
let anonymousVariation = anonymousKameleoonClient.getVariation(featureKey)
// 2. After the visitor is authenticated
// Assume `userId` is the visitor code of the authenticated visitor.
anonymousKameleoonClient.addData(CustomData(id: mappingIndex, values: userId))
anonymousKameleoonClient.flush(instant: true)
KameleoonClient userKameleoonClient = KameleoonClientFactory.create(
siteCode: siteCode,
visitorCode: userId,
config: KameleoonClientConfig(
isUniqueIdentifier: true // Indicate that `userId` is a unique identifier
)
)
try await userKameleoonClient.runWhenReady()
// 3. After the visitor has been authenticated
// Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
let userVariation = userKameleoonClient.getVariation(featureKey: featureKey)
let isSameVariation = userVariation.key == anonymousVariation.key // true
// The `userId` and `anonymousVisitorCode` are now linked and tracked as a single visitor.
userKameleoonClient.trackConversion(goalId: 123, revenue: 10.0);
// Additionally, the linked visitors will share all fetched remote visitor data.
try await userKameleoonClient.getRemoteVisitorData()
En este ejemplo, la aplicación tiene una página de inicio de sesión. Como el ID de usuario es desconocido en el momento del inicio de sesión, se utiliza un visitante anónimo generado automáticamente por el SDK. El visitor code puede recuperarse con el método getVisitorCode(). Después de que el usuario inicia sesión, el visitante anónimo se asocia con el ID de usuario y se utiliza como identificador único del visitante.
Uso de una clave de bucketing personalizada
De forma predeterminada, Kameleoon utiliza un ID de visitante anónimo y único (visitorCode) para asignar usuarios a las variaciones de los feature flags. Este ID se genera y almacena habitualmente en el dispositivo del usuario (en una cookie del navegador para los SDKs del lado del cliente y del lado del servidor, y en almacenamiento persistente para los SDKs móviles). Sin embargo, en determinados escenarios puede necesitar asegurarse de que todos los usuarios de la misma organización vean la misma variante de un feature flag.
La opción Custom Bucketing Key le permite anular este comportamiento predeterminado proporcionando su propio identificador personalizado para el bucketing. Esta anulación garantiza que la lógica de asignación de Kameleoon utilice la clave que usted especifique en lugar del visitorCode predeterminado.
Casos de uso
El uso de una clave de bucketing personalizada es esencial para mantener la consistencia y precisión en las asignaciones de sus feature flags, especialmente en estas situaciones:
- Experimentos a nivel de cuenta u organización: Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como
accountId. Las claves de bucketing personalizadas son cruciales para probar mediante A/B funcionalidades que afecten a todo un equipo o empresa.
Al implementar una clave de bucketing personalizada, garantiza una mayor consistencia y precisión en sus experimentos, lo que se traduce en resultados más fiables y en una mejor experiencia de usuario.
Detalles técnicos
Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico de los datos de su aplicación:
try? kameleoonClient.addData(CustomData(id: index, values: "newVisitorCode"))
- Proporcionar la clave personalizada: Usted proporciona su identificador personalizado al SDK de Kameleoon mediante el método
addData(). En este método, pasará la clave de bucketing personalizada que haya elegido como un objeto CustomData. Aquí, newVisitorCode hace referencia al identificador que desea usar para el bucketing (por ejemplo, el nuevo userId o accountId).
Para que la clave de bucketing personalizada funcione correctamente, también debe definirse y configurarse para el feature flag durante el proceso de creación o edición del flag. Sin esta configuración correspondiente, el bucketing del SDK no aplicará su clave personalizada. Para obtener instrucciones detalladas sobre cómo configurar esto en Kameleoon, consulte este artículo.
- Lógica de bucketing: Una vez que se proporciona una clave de bucketing personalizada a través del método
addData(), todos los cálculos de hash para asignar usuarios a las variaciones utilizarán este newVisitorCode (su clave personalizada) en lugar del visitorCode predeterminado. Usar el newVisitorCode significa que la decisión de bucketing queda ligada a su identificador personalizado, garantizando asignaciones consistentes en los diversos contextos en los que esté presente ese identificador.
- Seguimiento de datos y analítica: Es crucial tener en cuenta que, aunque el
newVisitorCode (su clave personalizada) se utiliza para las decisiones de bucketing, todos los datos posteriores (eventos de seguimiento y conversiones, por ejemplo) se envían y se asocian con el visitorCode original. Esta separación garantiza que su analítica refleje con precisión los recorridos e interacciones individuales de los usuarios dentro del contexto más amplio de su experimento, incluso cuando el bucketing se realiza a un nivel superior (como una cuenta) o a través de varios dispositivos/sesiones. Sus datos originales del visitante permanecen intactos para una elaboración de informes completa.
Requisitos técnicos
Para utilizar eficazmente una clave de bucketing personalizada:
- La clave debe ser un
String.
- Debe ser única para la entidad que pretende agrupar (por ejemplo, si utiliza un
userId, el ID de cada usuario debe ser único).
- La clave debe estar disponible para el SDK en el momento exacto en que se evalúa la decisión del feature flag para ese usuario o solicitud.
Condiciones de segmentación
Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede usar para segmentar a los usuarios en sus campañas. Para ver la lista de condiciones que admite este SDK, consulte usar el historial de visitas para segmentar a los usuarios.
También puede utilizar sus propios datos externos para segmentar a los usuarios.
Registro de eventos
El SDK genera registros que reflejan diversos procesos internos y problemas.
Niveles de registro
El SDK admite la configuración para limitar el registro mediante un nivel de log.
// The `none` log level does not allow logging.
KameleoonLogger.logLevel = .none
// The `ERROR` log level only allows logging issues that may affect the SDK's main behaviour.
KameleoonLogger.logLevel = .error
// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
KameleoonLogger.logLevel = .warning
// The `INFO` log level allows logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
KameleoonLogger.logLevel = .info
// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular. diagnostic output.
// This information is not intended for end-user interpretation but can be sent to support
// to assist with internal troubleshooting.
KameleoonLogger.logLevel = .debug
Gestión personalizada de los registros
El SDK escribe sus registros en la salida de la consola de forma predeterminada. Este comportamiento puede anularse.
El filtrado por nivel de log se realiza de forma independiente de la lógica de gestión de los registros.
public struct CustomLogger: Logging {
let customLogger = Logger(subsystem: "com.yourcompany.app", category: "app")
public func log(level: LogLevel, message: String) {
switch level {
case .error:
customLogger.error("\(message)")
case .warning:
customLogger.warning("\(message)")
case .info:
customLogger.info("\(message)")
case .debug:
customLogger.debug("\(message)")
default:
break
}
}
}
// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
KameleoonLogger.logLevel = .debug // Optional, defaults to `LogLevel.WARNING`.
KameleoonLogger.logger = CustomLogger()
Passing the visitor code to a WebView
In some cases, you may need to pass the visitor code from the native application to a WebView that uses Engine.js or the web JavaScript or React SDKs. The following example demonstrates the recommended way to achieve this:
SwiftUI
SwiftUI (iOS 26+)
struct WebView: UIViewRepresentable {
let url: URL
let kameleoonClient: KameleoonClient
private let kameleoonCookieName = "kameleoonVisitorCode"
func makeUIView(context: Context) -> WKWebView {
let config = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero, configuration: config)
let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
let cookie = makeVisitorCookie()
cookieStore.setCookie(cookie) {
webView.load(URLRequest(url: url))
}
return webView
}
func updateUIView(_ webView: WKWebView, context: Context) {}
private func makeVisitorCookie() -> HTTPCookie {
let properties: [HTTPCookiePropertyKey: Any] = [
.domain: ".example.com",
.path: "/",
.name: kameleoonCookieName,
.value: kameleoonClient.visitorCode,
.secure: true,
.expires: Date(timeIntervalSinceNow: 60 * 60 * 24 * 365)
]
return HTTPCookie(properties: properties)!
}
}
struct WebView: View {
let url: URL
let kameleoonClient: KameleoonClient
private let websiteDataStore: WKWebsiteDataStore
private let kameleoonCookieName = "kameleoonVisitorCode"
@State private var page: WebPage
init(url: URL, kameleoonClient: KameleoonClient) {
self.url = url
self.kameleoonClient = kameleoonClient
let websiteDataStore = WKWebsiteDataStore.default()
var configuration = WebPage.Configuration()
configuration.websiteDataStore = websiteDataStore
self.websiteDataStore = websiteDataStore
_page = State(initialValue: WebPage(configuration: configuration))
}
var body: some View {
WebView(page)
.webViewBackForwardNavigationGestures(.enabled)
.task(id: url) {
let cookieStore = websiteDataStore.httpCookieStore
let properties: [HTTPCookiePropertyKey: Any] = [
.domain: ".example.com",
.path: "/",
.name: kameleoonCookieName,
.value: kameleoonClient.visitorCode,
.secure: true
]
if let cookie = HTTPCookie(properties: properties) {
await cookieStore.setCookie(cookie)
}
page.load(URLRequest(url: url))
}
}
}
Apple privacy compliance
Starting May 1st, 2024, Apple requires apps that include a third-party SDK, such as the Kameleoon iOS SDK, that include a privacy manifest file. The latest version of the SDK is code-signed, compliant, and includes a valid manifest file with the SDK. No action is required if you’re using the Kameleoon iOS SDK version 4.2 or later.
Referencia
This is the full reference documentation for the Kameleoon iOS (Swift) SDK.
Inicialización
Once you have installed the SDK in your application, you must initialize Kameleoon. All of your application’s interactions with the SDK, such as triggering an experiment, are accomplished using this Kameleoon client object.
create()
Llame a este método antes que a cualquier otro para inicializar el SDK. Este método se encuentra en KameleoonClientFactory. create() crea una instancia de KameleoonClient para gestionar todas las interacciones entre el SDK y su aplicación.
Puede personalizar el comportamiento del SDK (por ejemplo, el entorno, las credenciales) proporcionando un objeto de configuración. De lo contrario, el SDK intentará encontrar su archivo de configuración y lo usará.
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
trackingIntervalMillisecond: 500, // optional, 1000 milliseconds by default
environment: "production", // optional
isUniqueIdentifier: false, // optional, false by default. Set to true if the visitorCode corresponds to your customer's unique userId.
networkDomain: "example.com", // optional, nil by default
defaultDataFile: "{...}", // optional, nil by default
activityTrackingIntervalMillisecond: 20_000 // optional, 15_000 milliseconds by default
)
let kameleoonClient = try KameleoonClientFactory.create(
siteCode: siteCode,
visitorCode: visitorCode, // optional
config: config // optional
)
} catch KameleoonError.visitorCodeInvalid {
// Provided visitor code is invalid
} catch KameleoonError.siteCodeIsEmpty {
// Indicates that provided site code is empty
} catch {
// Unexpected error occurred
}
do {
// read client configuration from a file 'kameleoon-client-swift.plist'
// visitor code isn't provided, so SDK generates a random visitor code which will be used in the future
let kameleoonClient = KameleoonClientFactory.create(siteCode: siteCode)
} catch KameleoonError.visitorCodeInvalid {
// Provided visitor code is invalid
} catch KameleoonError.siteCodeIsEmpty {
// Indicates that provided site code is empty
} catch {
// Unexpected error occurred
}
Argumentos
| Name | Type | Description | Default |
|---|
| siteCode (obligatorio) | String | A unique key identifying the Kameleoon project used with the SDK. | |
| visitorCode (opcional) | String? | An optional visitor identifier. If available, use your internal user ID; otherwise, the SDK will generate one automatically. | nil |
| config (opcional) | KameleoonClientConfig? | Optional SDK configuration. If provided, it is used instead of reading from an external configuration file. If not provided, the SDK attempts to read the file, but if the file is missing, it falls back to default behavior. | nil |
Valor de retorno
| Tipo | Descripción |
|---|
KameleoonClient | Una instancia de la clase KameleoonClient que su aplicación puede utilizar para gestionar sus experimentos y feature flags. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
KameleoonError.visitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
KameleoonError.siteCodeIsEmpty | Excepción que indica que el site code especificado es una cadena vacía, lo que no es un valor válido. |
ready
For mobile SDKs, the Kameleoon Client’s initialization is not immediate. The SDK needs to perform a server call to retrieve the current configuration for all active experiments. Check if the SDK is ready by calling this method before triggering an experiment. Alternatively, you can use the runWhenReady() method with a callback.
let ready = kameleoonClient.ready
Valor de retorno
| Name | Type | Description |
|---|
| ready | Bool | Boolean representing the status of the SDK (true if fully initialized, false if not ready to be used). |
runWhenReady()
- 🔄 Performs an asynchronous request (if the configuration is outdated or missing)
For mobile SDKs, the KameleoonClient cannot initialize immediately, as it needs to perform a server call to retrieve the current configuration for all feature flags. Use the runWhenReady() method to wait until the client is ready for use. Additionally, you can set a maximum timeout period to control how long the client will wait before it becomes ready.
If ready=true, the KameleoonClient is fully initialized, and feature flags will be evaluated and assigned their respective variations. If the result is false or a timeout occurs, the initialization will not complete.
El callback o el código asíncrono debe encargarse de aplicar la variación de referencia, ya que un timeout excluirá al usuario del feature flag.
Since the initial configuration may require a server call, this mechanism is asynchronous. Therefore, you should either:
- Provide a
completion callback as an argument to the method to ensure you are notified when the KameleoonClient is fully initialized and ready for use.
- Use asynchronous operations.
func applyRecommendedProductsVariation() {
let defaultValue = 5 // Default control number for recommended products
kameleoonClient.runWhenReady(timeoutMilliseconds: 1000) { ready in
guard ready else {
applyVariation(recommendedProductsNumber: defaultValue)
return
}
let variation = try? kameleoonClient.getVariation(featureKey: "featureKey")
let recommendedProductsNumber = variation.variables["recommendedProductsNumber"]?.value as? Int ?? defaultValue
applyVariation(recommendedProductsNumber: recommendedProductsNumber)
}
}
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| timeoutMilliseconds (opcional) | Int | Timeout for the initialization process | defaultTimeoutMillisecond or default_timeout_millisecond |
| callback (obligatorio) | (Bool) -> Void | Callback object. It is a lambda expression that will get a Bool argument representing whether the KameleoonClient became ready before the timeout was reached. | |
A common mistake is calling async functions with try? or inside a nested do-catch block without rethrowing CancellationError. This can interfere with task cancellation, causing unexpected behavior.
To ensure correct task cancellation, avoid using try? or do-catch around async functions unless you explicitly rethrow CancellationError.
func applyRecommendedProductsVariation() async throws {
let defaultValue = 5 // Default control number for recommended products
try await kameleoonClient.runWhenReady(timeoutMilliseconds: 1000)
let variation = try kameleoonClient.getVariation(featureKey: "featureKey")
let recommendedProductsNumber = variation.variables["recommendedProductsNumber"]?.value as? Int ?? defaultValue
applyVariation(recommendedProductsNumber: recommendedProductsNumber)
}
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| timeoutMilliseconds (opcional) | Int | Timeout for the initialization process | defaultTimeoutMillisecond or default_timeout_millisecond |
Errores thrown
| Type | Description |
|---|
KameleoonError.sdkNotReady | Exception indicating that the SDK is not fully initialized yet. |
Feature flags y variaciones
isFeatureActive()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
This method was previously called activateFeature, which was removed in SDK version 4.0.0.
To activate a feature toggle, call this method. isFeatureActive() accepts featureKey as a required argument to check if the specified feature will be active for a visitor.
If a visitor has never been associated with this feature flag, this method returns a random boolean value (true if the user should be shown this feature, otherwise false). If the visitor is already registered with this feature flag, the method returns the previous featureFlag value.
Ensure you implement error handling como se muestra en el ejemplo code to catch potential errors.
Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as isFeatureActive(), getVariation() or getVariations().Use el valor predeterminado true para el parámetro track cuando exponga a los visitantes a una variación y necesite contarlos. Establezca el parámetro track en false solo si llama a estos métodos antes de exponer a los visitantes.Por ejemplo, if you call getVariations() to retrieve all variations before you expose visitors, set the track parameter to false. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
let featureKey = "new_checkout"
var hasNewCheckout = false
do {
hasNewCheckout = try kameleoonClient.isFeatureActive(featureKey: featureKey)
// disabling tracking
hasNewCheckout = kameleoonClient.isFeatureActive(featureKey: featureKey, track: false);
} catch {
switch error {
case KameleoonError.sdkNotReady:
// Exception indicating that the SDK has not completed its initialization yet.
hasNewCheckout = false
case KameleoonError.Feature.notFound:
// The feature key is not in the configuration file that has been fetched by the SDK.
hasNewCheckout = false
default:
// Any other error.
hasNewCheckout = false
}
}
if hasNewCheckout
{
// Implement new checkout code here
}
The isFeatureActive() method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the Then, for everyone else serve default state. If you select Off for this default state, the method always returns false even when the master feature flag is On.
Argumentos
| Name | Type | Description |
|---|
| featureKey | String | The key of the feature you want to expose to a user. Este campo es obligatorio. |
| track | Bool | An optional parameter to enable or disable feature evaluation tracking (true by default). |
Valor de retorno
| Type | Description |
|---|
Bool | Value of the feature that is registered for the visitor. |
Errores thrown
| Type | Description |
|---|
KameleoonError.sdkNotReady | Exception indicating that the SDK is not fully initialized. |
KameleoonError.Feature.notFound | Exception indicating that the requested feature ID has not been found in the SDK’s internal configuration. This exception usually means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed in the web-application). |
getVariation()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Recupera la Variation asignada a un visitante dado para un feature flag específico.
Este método toma un visitorCode and featureKey as mandatory arguments. The track argument is optional and defaults to true.
Devuelve la Variation asignada al visitante. Si el visitante no está asociado con ninguna regla de feature flag, el método devuelve la Variation predeterminada para el feature flag dado.
Asegúrese de implementar un manejo de errores adecuado en su código para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
let featureKey = "featureKey"
var variation: Types.Variation?
do {
variation = try kameleoonClient.getVariation(featureKey: featureKey)
// disabling tracking
variation = kameleoonClient.getVariation(featureKey: featureKey, track: false);
} catch {
switch error {
case KameleoonError.sdkNotReady:
// Exception indicating that the SDK has not completed its initialization yet.
case KameleoonError.Feature.notFound:
// The feature key is not in the configuration file that has been fetched by the SDK.
case KameleoonError.Feature.environmentDisabled:
// The feature flag is disabled for the environment.
default:
// Any other error.
}
}
let title = variation?.variables["title"].value
switch variation?.key {
case "on":
// Main variation key is selected for visitorCode
case "alternative_variation":
// Alternative variation key
default:
// Default variation key
}
Argumentos
| Name | Type | Description | Default |
|---|
| visitorCode (obligatorio) | String | Identificador único del visitante. | |
| featureKey (obligatorio) | String | Clave de la funcionalidad que desea exponer a un visitante. | |
| track (opcional) | Bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|
Variation | An assigned Variation to a given visitor for a specific feature flag. |
Errores thrown
| Tipo | Descripción |
|---|
KameleoonError.visitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
KameleoonError.Feature.notFound | Excepción que indica que la clave de funcionalidad solicitada no se encontró en la configuración interna del SDK. Esto suele significar que el feature flag no está activado en la aplicación de Kameleoon (pero el código que implementa la funcionalidad ya está desplegado en la aplicación). |
KameleoonError.Feature.environmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
getVariations()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Recupera un map de objetos Variation asignados a un visitante dado para todos los feature flags.
Este método itera sobre todos los feature flags disponibles y devuelve la Variation asignada para cada flag asociado con el visitante especificado. It takes onlyActive and track as optional arguments.
- Si
onlyActive se establece en true, el método getVariations() devolverá las variaciones de los feature flags siempre que el usuario no esté asignado a la variación off.
- El parámetro
track controla si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set to true. Si se establece en false, el seguimiento estará deshabilitado.
El map devuelto consta de claves de feature flags como claves y su Variation correspondiente como valores. Si no se asigna ninguna variación para un feature flag, el método devuelve la Variation predeterminada para ese flag.
Se debe implementar un manejo de errores adecuado para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
do {
let variations = kameleoonClient.getVariations();
// only active variations
let variations = kameleoonClient.getVariations(onlyActive: true);
// disable tracking
let variations = kameleoonClient.getVariations(track: false);
} catch KameleoonError.sdkNotReady {
// Exception indicating that the SDK has not completed its initialization yet.
}
Argumentos
| Name | Type | Description | Default |
|---|
| onlyActive (opcional) | Bool | Parámetro opcional que indica si se deben devolver las variaciones para los feature flags activos (true) o todos (false). | false |
| track (opcional) | Bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|
Dict<String, Variation> | Map que contiene los objetos Variation asignados de los feature flags utilizando las claves de las funcionalidades correspondientes. |
Errores thrown
| Tipo | Descripción |
|---|
KameleoonError.sdkNotReady | Indicates that the SDK is not yet fully initialized. |
setForcedVariation()
El método permite you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. Esto es especialmente valioso para experimentos controlados donde la lógica de evaluación habitual no es necesaria o debe omitirse. It can also be helpful in scenarios like debugging or custom testing.
Cuando se establece una variación forzada, esta anula la lógica de evaluación en tiempo real de Kameleoon. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set forceTargeting=false instead.
A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.
El método puede lanzar excepciones bajo ciertas condiciones (por ejemplo, parámetros no válidos, contexto del usuario o problemas internos). Proper exception handling is essential to ensure that your application remains stable and resilient.
let experimentId = 9516
do {
// Forcing the variation "on" for the experiment 9516 for the visitor
try kameleoonClient.setForcedVariation(experimentId: experimentId, variationKey: "on")
// Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment
try kameleoonClient.setForcedVariation(experimentId: experimentId, variationKey: "on", forceTargeting: false)
// Resetting the forced variation for the experiment 9516 for the visitor
try kameleoonClient.setForcedVariation(experimentId: experimentId, variationKey: nil);
} catch {
// Handling the KameleoonError, KameleoonError.Feature and common Error
}
Argumentos
| Name | Type | Description | Default |
|---|
| experimentId (obligatorio) | Int | Experiment Id que será segmentado y seleccionado durante el proceso de evaluación. | |
| variationKey (obligatorio) | String | Variation Key correspondiente a una Variation que debe forzarse como valor devuelto para el experimento. If the value is nil, the forced variation will be reset. | |
| forceTargeting (opcional) | Bool | Indica si la segmentación para el experimento debe forzarse y omitirse (true) o aplicarse como en el proceso de evaluación estándar (false). | true |
Errores thrown
| Tipo | Descripción |
|---|
KameleoonError.sdkNotReady | Indicates that the SDK is not yet fully initialized. |
KameleoonError.Feature.experimentNotFound | Excepción que indica que el experiment id solicitado no se encontró en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la regla todavía no se ha activado del lado de Kameleoon. |
KameleoonError.Feature.variationNotFound | Excepción que indica que la variation key (id) solicitada no se ha encontrado en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon. |
In most cases, only the basic error, KameleoonError/KameleoonError.Feature, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Error.
evaluateAudiences()
- 📨 Envía datos de seguimiento a Kameleoon
Este método evalúa a los visitantes con respecto a todos los segmentos disponibles de Audiences Explorer y realiza el seguimiento de los que coinciden.
evaluateAudiences() should be called after all relevant visitor data has been set or updated, and just before getting a feature variation or checking a feature flag. Este enfoque garantiza que el visitante se evalúe con los datos más recientes disponibles, lo que permite una asignación precisa de audiencia basada en todos los criterios.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
do {
try kameleoonClient.evaluateAudiences();
} catch {
// Handling the errors
}
Errores thrown
| Tipo | Descripción |
|---|
KameleoonError.sdkNotReady | Indicates that the SDK is not yet fully initialized. |
In most cases, only the basic error, KameleoonError/KameleoonError.Feature, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Error.
getFeatureList()
Devuelve una lista de claves de feature flags disponibles actualmente en el SDK.
let allFeatureList = kameleoonClient.getFeatureList()
Valor de retorno
| Tipo | Descripción |
|---|
[String] | List of feature flag keys |
getDataFile()
To evaluate all feature flags, use getVariations(). Este método es más eficiente que llamar a DataFile e iterar por los flags con getVariation().
Devuelve la configuración actual del SDK como un objeto DataFile.
do {
let dataFile = try kameleoonClient.getDataFile()
} catch KameleoonError.sdkNotReady {
// Exception indicates that the SDK has not completed its initialization yet.
} catch {
// Handling the KameleoonError, KameleoonError.Feature and common Error
}
Valor de retorno
| Tipo | Descripción |
|---|
DataFile | El DataFile que contiene la configuración del SDK |
Errores thrown
| Tipo | Descripción |
|---|
KameleoonError.sdkNotReady | Indicates that the SDK is not yet fully initialized. |
Goals
trackConversion()
- 📨 Envía datos de seguimiento a Kameleoon
Use este método para realizar el seguimiento de conversiones. Este método requiere goalId para hacer seguimiento de la conversión en este objetivo en particular. Además, este método también acepta los argumentos revenue, metadata y negative.
El método trackConversion() no devuelve ningún valor. Este método no es bloqueante, ya que la llamada al servidor se realiza de forma asíncrona.
let goalId = 83023
kameleoonClient.trackConversion(goalId: goalId, revenue: 10.0)
kameleoonClient.trackConversion(goalId: goalId, revenue: 10.0, metadata: CustomData(id: 1, values: "metadata"))
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| goalId (obligatorio) | Int | ID del objetivo. | |
| revenue (opcional) | Double | Ingreso de la conversión. | 0 |
| negative (opcional) | Bool | Define si el ingreso es positivo o negativo. | false |
| metadata (opcional) | CustomData... / [CustomData] | Metadatos de la conversión. Must be defined beforehand in the Kameleoon App. | [] |
metadata values are accessible through raw data exports and the results page.Si se proporciona el parámetro metadata, Kameleoon utilizará estos valores especificados para la conversión actual en lugar de lo recopilado previamente mediante el método addData(). Si se omite el parámetro, Kameleoon utilizará los últimos valores rastreados para esos CustomData antes de la conversión y dentro de la misma visita.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the trackConversion() method.En el siguiente ejemplo, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).kameleoonClient.addData([CustomData(id: 5, values: "Credit Card"), CustomData(id: 9, "Express Delivery")]);
kameleoonClient.trackConversionWithOptParams(goalId: 1000, metadata: CustomData(5, "Amex Credit Card"));
Events
updateConfigurationHandler()
El método updateConfigurationHandler() le permite gestionar el evento cuando la configuración tiene datos actualizados. Toma un parámetro de entrada, handler. El manejador que se llamará cuando la configuración se actualice mediante un evento de configuración en tiempo real.
kameleoonClient.updateConfigurationHandler {
// configuration was updated
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| handler | Optional<(() -> Void)> | The handler that will be called when the configuration is updated using a real-time configuration event. |
Datos del visitante
visitorCode
Returns unique visitor code used in SDK.
let visitorCode = kameleoonClient.visitorCode
Valor de retorno
| Tipo | Descripción |
|---|
String | String representing a unique visitor code used in SDK. |
addData()
El método addData() añade datos de segmentación al almacenamiento para que otros métodos puedan utilizar los datos para decidir si segmentar o no al visitante actual.
El método addData() no devuelve ningún valor y no interactúa por sí mismo con los servidores backend de Kameleoon. En su lugar, todos los datos declarados se guardan para su transmisión futura mediante el método flush(). Este enfoque reduce el número de llamadas al servidor, ya que los datos se agrupan habitualmente en una única llamada al servidor que desencadena el flush().
El método trackConversion() también envía cualquier dato previamente asociado, al igual que flush(). The same holds true for getVariation() and getVariations() methods if an experimentation rule is triggered.
Cada visitante solo puede tener una instancia de datos asociados para la mayoría de los tipos de datos. However, CustomData is an exception. Visitors can have one instance of associated CustomData per index.
// Add a single data item (tracked by default)
kameleoonClient.addData(CustomData(index: 1, values: "value"))
// Add multiple data items (tracked by default)
kameleoonClient.addData(
CustomData(index: 20, values: "value"),
Geolocation(country: "France")
)
// Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
kameleoonClient.addData(
track: false,
CustomData(index: 20, values: "value"),
Geolocation(country: "France")
)
Argumentos
| Nombre | Tipo | Descripción | Valor predeterminado |
|---|
| track (opcional) | Bool | Especifica si los datos añadidos son aptos para el seguimiento. Cuando se establece en false, los datos se almacenan localmente y se utilizan solo para la evaluación de segmentación; no se envían a la Data API de Kameleoon. | true |
| data (obligatorio) | KameleoonData... / [KameleoonData] | Colección de tipos de datos de Kameleoon. | |
flush()
- 📨 Envía datos de seguimiento a Kameleoon
El método flush() recopila los datos de Kameleoon vinculados al visitante. It then sends a tracking request, along with all data added using the addData method that has not yet been sent using one of these methods. flush() is non-blocking as the server call is made asynchronously.
flush provides control over when data associated with a given visitorCode is sent to the servers. For instance, if addData() is called a dozen times, sending data to the server each time addData() is invoked would be inefficient. Call flush() once.
kameleoonClient.addData(CustomData(id: 20, values: "true", "20"))
kameleoonClient.addData(Conversion(goalId: 32, revenue: 10.0, negative: false))
kameleoonClient.flush() // Interval tracking (most performant way for tracking)
kameleoonClient.flush(instant: true) // Instant tracking
Argumentos
| Name | Type | Description |
|---|
| instant | Bool | Boolean flag indicating whether the data should be sent instantly (true) or according to the default tracking interval (false) set with the SDK parameter trackingIntervalMillisecond in KameleoonClientConfig or tracking_interval_millisecond. Este campo es opcional. |
Errores thrown
| Type | Description |
|---|
KameleoonError.sdkNotReady | Error indicating that the SDK has not completed its initialization. |
getRemoteData()
- 🔄 Performs an asynchronous request
This method was previously called retrieveDataFromRemoteSource, which was removed in SDK version 4.0.0 release.
Use este método para retrieve data from a remote Kameleoon server based on the active siteCode and the key argument (or the active visitorCode if the key is omitted). The visitorCode and siteCode are specified in KameleoonClientFactory.create(). Data can be stored quickly and conveniently on highly scalable remote servers using the Kameleoon Data API. The application can then retrieve the data using this method.
Since a server call is required, this mechanism is asynchronous. Therefore, you should either:
- Provide a
completion callback as an argument to the method to ensure you are notified when the data has been successfully fetched.
- Use asynchronous operations.
struct Test1: Decodable {
let value: String
private enum CodingKeys: String, CodingKey {
case value = "json_value"
}
}
kameleoonClient.getRemoteData(key: "test") { (result: Result<Test1, Error>) in
switch result {
case .success(let test1):
// test1 is a decoded value for Test1 type
case .failure:
// error includes 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 includes informaion about request's failure
}
}
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| key (opcional) | String | The key that the data you want to get is associated with. | "" |
| completion (obligatorio) | (Result<T: Decodable, Error>) -> Void | The callback that processes the received data. | |
A common mistake is calling async functions with try? or inside a nested do-catch block without rethrowing CancellationError. This can interfere with task cancellation, causing unexpected behavior.
To ensure correct task cancellation, avoid using try? or do-catch around async functions unless you explicitly rethrow CancellationError.
struct Test1: Decodable {
let value: String
private enum CodingKeys: String, CodingKey {
case value = "json_value"
}
}
Task {
do {
let test1: Test1 = try await kameleoonClient.getRemoteData(key: "test")
// test1 is a decoded value for Test1 type
} catch {
// handle error
}
}
Task {
do {
let data: Data = try await kameleoonClient.getRawRemoteData(key: "test")
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
} catch {
// handle error
}
}
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| key (opcional) | String | The key that the data you want to get is associated with. | "" |
Return Value
| Tipo | Descripción |
|---|
Decodable | A Decodable object containing the parsed fetched value. |
Errores thrown
| Tipo | Descripción |
|---|
Error | Indicates that the request has failed due to an error. |
getRemoteVisitorData()
- 🔄 Performs an asynchronous request
getRemoteVisitorData() is an asynchronous method for retrieving Kameleoon Visits Data for the visitor from the Kameleoon Data API. El método añade los datos al almacenamiento para que otros métodos los utilicen al tomar decisiones de segmentación.
Los datos obtenidos mediante este método desempeñan un papel importante cuando desea:
- utilizar datos recopilados desde otros dispositivos.
- access a user’s history, such as custom data collected during previous visits.
Read this article for a better understanding of possible use cases.
De forma predeterminada, getRemoteVisitorData() automatically retrieves the latest stored custom data with scope=Visitor and attaches them to the visitor without the need to call the method addData(). It is particularly useful for synchronizing custom data between multiple devices.Checking only for failed results is recommended. However, if necessary, it can be verified that the data has been added to the visitor and is available for targeting purposes (or for debugging, though using logging is better for debugging). Additionally, data can be managed manually if the addData=false parameter is passed.
Since a server call is required, this mechanism is asynchronous. Therefore, you should either:
- Provide a
completion callback as an argument to the method to ensure you are notified when the data has been successfully fetched and added to the visitor.
- Use asynchronous operations.
// Fetch visitor data and automatically add it
kameleoonClient.getRemoteVisitorData { result in
switch result {
case .success(let visitorData):
// visitorData includes all retrieved data that was added for the visitor
case .failure:
// Handle the error, which contains information about the request failure
}
}
// Fetch visitor data without automatically adding it
kameleoonClient.getRemoteVisitorData(addData: false) { result in
switch result {
case .success(let visitorData):
// visitorData includes all retrieved data that was added for the visitor
case .failure:
// Handle the error, which contains information about the request failure
}
}
// Fetch a custom list of data types
let filter = Types.RemoteVisitorDataFilter(
previousVisitAmount: 25, currentVisit: true, conversions: true, experiments: true, geolocation: true
)
kameleoonClient.getRemoteVisitorData(filter: filter) { result in
switch result {
case .success(let visitorData):
// visitorData includes all retrieved data that was added for the visitor
case .failure:
// Handle the error, which contains information about the request failure
}
}
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| filter (opcional) | RemoteVisitorDataFilter | Filter that selects which data should be retrieved from visit history. De forma predeterminada, the method retrieves CustomData from the current and latest previous visit. | RemoteVisitorDataFilter.default |
| addData (opcional) | Boolean | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. | true |
| completion (obligatorio) | (Result<[KameleoonData], Error>) -> Void | The callback that processes the received visitor data. | |
A common mistake is calling async functions with try? or inside a nested do-catch block without rethrowing CancellationError. This can interfere with task cancellation, causing unexpected behavior.
To ensure correct task cancellation, avoid using try? or do-catch around async functions unless you explicitly rethrow CancellationError.
// Fetch visitor data and automatically add it
Task {
do {
let visitorData = try await kameleoonClient.getRemoteVisitorData()
// visitorData includes all retrieved data that was added for the visitor
} catch {
// Handle the error, which contains information about the request failure
}
}
// Fetch visitor data without automatically adding it
Task {
do {
let visitorData = try await kameleoonClient.getRemoteVisitorData(addData: false)
// visitorData includes all retrieved data but was not added for the visitor
} catch {
// Handle the error, which contains information about the request failure
}
}
// Fetch a custom list of data types
Task {
do {
let filter = Types.RemoteVisitorDataFilter(
previousVisitAmount: 25, currentVisit: true, conversions: true, experiments: true, geolocation: true
)
let visitorData = try await kameleoonClient.getRemoteVisitorData(filter: filter)
// visitorData includes all retrieved data based on the specified filter
} catch {
// Handle the error, which contains information about the request failure
}
}
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| filter (opcional) | RemoteVisitorDataFilter | Filter that selects which data should be retrieved from visit history. De forma predeterminada, the method retrieves CustomData from the current and latest previous visit. | RemoteVisitorDataFilter.default |
| addData (opcional) | Boolean | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. | true |
Return Value
| Tipo | Descripción |
|---|
[KameleoonData] | An array containing the fetched data for the visitor. |
Errores thrown
| Tipo | Descripción |
|---|
Error | Indicates that the request has failed due to an error. |
Using parameters with RemoteVisitorDataFilter
El método getRemoteVisitorData() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Whether you’re targeting based on goals, experiments, or variations, the same approach applies across all data types.
Por ejemplo, suppose you want to retrieve data on visitors who completed a goal “Order transaction”. Puede especificar parámetros dentro del método getRemoteVisitorData() para refinar su segmentación. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.
La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método getRemoteVisitorData() para recuperar datos sobre una variedad de comportamientos del visitante.
Here is the list of available Types.RemoteVisitorDataFilter options:| Name | Type | Description | Default |
|---|
| previousVisitAmount (opcional) | Int | Número de visitas previas de las que recuperar datos. Number between 1 and 25 | 1 |
| currentVisit (opcional) | Bool | If true, current visit data will be retrieved | true |
| customData (opcional) | Bool | If true, custom data will be retrieved. | true |
| conversions (opcional) | Bool | If true, conversion data will be retrieved. | false |
| experiments (opcional) | Bool | If true, experiment data will be retrieved. | false |
| geolocation (opcional) | Bool | If true, geolocation data will be retrieved. | false |
| kcs (opcional) | Bool | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
| visitorCode (opcional) | Bool | If true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. visitorCode is necessary if you want to ensure that the visitor, identified by their visitorCode, always receives the same variation across visits for Cross-device experimentation. | true |
| personalization (opcional) | Bool | If true, personalization data will be retrieved. personalization is required for the personalization condition | false |
| cbs (opcional) | Bool | If true, Contextual Bandit score data will be retrieved. | false |
getVisitorWarehouseAudience()
- 🔄 Performs an asynchronous request
Retrieves all audience data associated with the visitor in your data warehouse. The optional warehouseKey parameter is typically your internal user ID. The customDataIndex parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details.
Since a server call is required, this mechanism is asynchronous. Therefore, you should either:
- Provide a
completion callback as an argument to the method to ensure you are notified when the data has been successfully fetched and added to the visitor.
- Use coroutines for asynchronous handling.
Checking only for failed results is recommended. However, if necessary, it can be verified that the data has been added to the visitor and is available for targeting purposes (or for debugging, though using logging is better for debugging).
// Fetch visitor warehouse audience data
kameleoonClient.getVisitorWarehouseAudience(customDataIndex: 10) { result in
switch result {
case .success(let customData):
// Data was added. You can access it from `customData`
case .failure:
// Handle the error, which contains information about the request failure
}
}
// Fetch visitor warehouse audience data with a specific warehouse key
kameleoonClient.getVisitorWarehouseAudience(
warehouseKey: "warehouseKey", customDataIndex: 10
) { result in
switch result {
case .success(let customData):
// Data was added. You can access it from `customData`
case .failure:
// Handle the error, which contains information about the request failure
}
}
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| warehouseKey (opcional) | String | The unique key to identify the warehouse data (usually your internal user ID). | "" |
| customDataIndex (obligatorio) | Int | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences. | |
| completion | (Result<CustomData, Error>) -> Void | The callback that processes the received data. | |
A common mistake is calling async functions with try? or inside a nested do-catch block without rethrowing CancellationError. This can interfere with task cancellation, causing unexpected behavior.
To ensure correct task cancellation, avoid using try? or do-catch around async functions unless you explicitly rethrow CancellationError.
// Fetch visitor warehouse audience data
Task {
do {
let customData = try await kameleoonClient.getVisitorWarehouseAudience(customDataIndex: 10)
// Data was added. You can access it from `customData`
} catch {
// Handle the error, which contains information about the request failure
}
}
// Fetch visitor warehouse audience data with a specific warehouse key
Task {
do {
let customData = try await kameleoonClient.getVisitorWarehouseAudience(
warehouseKey: "warehouseKey", customDataIndex: 10
)
// Data was added. You can access it from `customData`
} catch {
// Handle the error, which contains information about the request failure
}
}
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| warehouseKey (opcional) | String | The unique key to identify the warehouse data (usually your internal user ID). | "" |
| customDataIndex (obligatorio) | Int | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences. | |
Return Value
| Tipo | Descripción |
|---|
CustomData | A CustomData entry added for a visitor. Generally, you can ignore this value, but it may be useful for testing purposes. |
Errores thrown
| Tipo | Descripción |
|---|
Error | Indicates that the request has failed due to an error. |
setLegalConsent()
You must use this method to specify whether the visitor has given legal consent to use their personal data. Setting the legalConsent parameter to false limits the types of data that you can include in tracking requests. This method helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.
Argumentos
| Name | Type | Description |
|---|
| legalConsent | boolean | Valor booleano que representa el estado del consentimiento legal. true indicates the visitor has given legal consent; false indicates the visitor has never provided, or has withdrawn, legal consent. Este campo es obligatorio. |
kameleoonClient.setLegalConsent(true)
Tipos de datos
This section lists the data types supported by Kameleoon. Several standard data types are provided, as well as the CustomData type for defining custom data types.
Conversion
El conjunto de datos Conversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
- Each visitor can have multiple
Conversion objects.
- You can find the
goalId in the Kameleoon app.
| Nombre | Tipo | Descripción | Default |
|---|
| goalId (obligatorio) | Int | ID del objetivo. | |
| revenue (opcional) | Double | Revenue of the conversion | 0 |
| negative (opcional) | Bool | Define si el ingreso es positivo o negativo. | false |
| metadata (opcional) | CustomData... / [CustomData] | Metadatos de la conversión. | [] |
kameleoonClient.addData(Conversion(goalId: 32, revenue: 10.0, negative: false))
kameleoonClient.addData(Conversion(goalId: 32, metadata: CustomData(id: 1, values: "metadata")))
CustomData
CustomData allows any type of data to be easily associated with each visitor. CustomData can then be used as a targeting condition in segments or as a filter/breakdown in experiment reports.
To learn more about custom data, please refer to this article.
| Nombre | Tipo | Descripción | |
|---|
| index/name (obligatorio) | Int/String | Índice o nombre del dato personalizado. Either index or name must be provided to identify the data. | |
| overwrite (opcional) | Bool | Flag para controlar explícitamente cómo se almacenan los valores y cómo aparecen en los informes. See more | true |
| values (obligatorio) | String... or [String] | Values of the custom data to be stored. | |
- Each visitor is allowed only one
CustomData for each unique index. Adding another CustomData with the same index will replace the existing CustomData.
- The custom data
index can be found in the Custom Data dashboard under the “INDEX” column.
- To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the Use this data only locally for targeting purposes option when creating custom data.
- Adding a
CustomData instance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
kameleoonClient.addData(CustomData(index: 1, values: "value"))
// With several values
kameleoonClient.addData(CustomData(index: 1, values: "value 1", "value 2"))
// To set the 'overwrite' flag to false
kameleoonClient.addData(CustomData(index: 1, overwrite: false, values: ["first value", "second value"]))
// To use a name instead of the index
kameleoonClient.addData(CustomData(name: "my-custom-data", values: "value"))
Device
Store information about the user’s device.
| Nombre | Tipo | Descripción |
|---|
| device | Device | List of devices: phone, tablet, desktop. Este campo es obligatorio. |
try? kameleoonClient.addData(Device.desktop);
Geolocation
Geolocation contains the visitor’s geolocation details.
| Nombre | Tipo | Descripción |
|---|
| country (obligatorio) | String | The country of the visitor. |
| region (opcional) | String? | The region of the visitor. |
| city (opcional) | String? | The city of the visitor. |
| postalCode (opcional) | String? | The postal code of the visitor. |
| latitude (opcional) | Double? | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
| longitude (opcional) | Double? | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
- Each visitor can have only one
Geolocation. Adding a second Geolocation overwrites the first one.
kameleoonClient.addData(Geolocation(country: "France", region: "Île-de-France", city: "Paris"));
Returned Types
DataFile
El DataFile contiene los detalles de configuración del SDK.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| featureFlags | [String: FeatureFlag] | A map of FeatureFlag objects, keyed by feature flag keys. |
| dateModified | Int | The timestamp (in milliseconds) indicating when the DataFile was last modified. |
// Retrieves the dictionary of feature flags from the DataFile.
// The dictionary is keyed by feature flag identifiers, with each value being a FeatureFlag object.
let featureFlags = dataFile.featureFlags
// Retrieves the last modification timestamp of the DataFile.
// The value is an Int representing milliseconds since the Unix epoch.
let dateModified = dataFile.dateModified
FeatureFlag
FeatureFlag representa un conjunto de propiedades que definen un feature flag en sí — por ejemplo, sus Variations, Rules, estado del entorno y otros detalles relacionados.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| environmentEnabled | Bool | Indica si el feature flag está habilitado en el entorno actual. |
| defaultVariationKey | String | The key of the default variation associated with the feature flag. |
| variations | [String: Variation] | A map of Variation objects, keyed by variation keys. |
| rules | [Rule] | A list of Rule objects |
// Check whether the feature flag is enabled in the current environment
let isEnvironmentEnabled = featureFlag.environmentEnabled
// Retrieve the key of the default variation
let defaultVariationKey = featureFlag.defaultVariationKey
// Retrieve the default variation object
let defaultVariation = featureFlag.defaultVariation
// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
let variations = featureFlag.variations
// Retrieve all targeting rules associated with the feature flag
let rules = featureFlag.rules
Rule
Rule representa un conjunto de propiedades que definen una regla en sí — por ejemplo, sus Variations.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| variations | [String: Variation] | A map of Variation objects, keyed by variation keys. |
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
let variations = rule.variations
Variation
Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
| Nombre | Tipo | Descripción |
|---|
| name | String | The name of the variation. |
| key | String | The unique key identifying the variation. |
| id | Int | The ID of the assigned variation (or -1 if it’s the default variation). |
| experimentId | Int | The ID of the experiment associated with the variation (or -1 if default). |
| variables | [String: Variable] | A map containing the variables of the assigned variation, keyed by variable names. variables could be an empty collection if no variables are associated. |
- The
Variation object provides details about the assigned variation and its associated experiment, while the Variable object contains specific details about each variable within a variation.
- Ensure that your code handles the case where
id or experimentId may be -1, indicating a default variation.
- The
variables map might be empty if no variables are associated with the variation.
// Retrieving the variation name
let variationName = variation.name
// Retrieving the variation key
let variationKey = variation.key
// Retrieving the variation id
let variationId = variation.id
// Retrieving the experiment id
let experimentId = variation.experimentId
// Retrieving the variables map
let variables = variation.variables
Variable
Variable contains information about a variable associated with the assigned variation.
| Nombre | Tipo | Descripción |
|---|
| key | String | The unique key identifying the variable. |
| type | String | The type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON. |
| value | Any? | The value of the variable, which can be of the following types: Bool, Int, Double, String, [String: Any] (json object), [Any] (json array). |
// Retrieving the variables map
let variables = variation.variables
// Variable type can be retrieved for further processing
let type = variables["isDiscount"]?.type ?? ""
// Get the bool value of "isDiscount" (default to false if missing or not a Bool)
let isDiscount = variables["isDiscount"]?.value as? Bool ?? false
// Get the numeric value of "number" as an Int (default to 0 if missing or not numeric)
let number = (variables["number"]?.value as? NSNumber)?.intValue ?? 0
// Get the String value of "title" (default to an empty string if missing or not a String)
let title = variables["title"]?.value as? String ?? ""
Deprecated methods
Estos métodos están obsoletos y se eliminarán en la versión 5.0.0 del SDK.
getFeatureVariationKey()
- 📨 Envía datos de seguimiento a Kameleoon
Use este método para get the feature variation key for a specific user. Este método toma un featureKey as a required argument to retrieve the variation key for the specified user.
If the visitor has never been associated with this feature flag, the SDK returns a randomly assigned variation key (according to the feature flag rules). If the visitor is already registered with this feature flag, this method returns the previous variation key. If the visitor does not match any of the rules, the default variation you defined in the Kameleoon app will be returned.
Ensure you set up proper error handling como se muestra en el ejemplo code to catch potential errors.
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 in the configuration file that has been fetched by the SDK. Trigger the old checkout for this visitor.
case KameleoonError.Feature.environmentDisabled:
// The feature flag is disabled for the environment.
default:
// Any other error.
}
}
getActiveFeatureList()
To get the list of feature flag keys currently available and active for the visitor.
let activeFeatureFlags = kameleoonClient.getActiveFeatureList()
Valor de retorno
| Tipo | Descripción |
|---|
| [String] | List of feature flag keys which are active for the visitor |
getActiveFeatures()
getActiveFeatures method retrieves information about the active feature flags that are available for the specified visitor code.
let activeFeatures = kameleoonClient.getActiveFeatures()
Valor de retorno
| Tipo | Descripción |
|---|
[String: Types.Variation] | A dictionary that contains the visitor’s assigned variations for each active feature using the keys of the corresponding active features. |
getFeatureVariable()
- 📨 Envía datos de seguimiento a Kameleoon
- Use
getVariation() instead.
- This method was previously called
obtainFeatureVariable(), which was removed in SDK version 4.0.0.
Llame a este método para obtener la variable de funcionalidad de una clave de variación asociada con un usuario.
Este método toma featureKey, and variableKey as required arguments to get the variable of the variation key for a given user.
If a visitor has never been associated with this feature flag, the SDK returns a variable value for the variation key that it randomly assigns according to the feature flag rules. If the user is already registered with this feature flag, the SDK returns the variable value for the previously associated variation. If the user does not match any of the rules, the default variable is returned.
String featureKey = "myFeature"
String variableKey = "myVariable"
try {
let variable = kameleoonClient.getFeatureVariable(featureKey: featureKey, variableKey: variableKey)
// your custom code, depending on variableValue
} catch {
switch error {
case KameleoonError.sdkNotReady:
// Exception indicating that the SDK has not completed its initialization.
case KameleoonError.Feature.notFound:
// The Feature Key is not in the configuration file that has been fetched by the SDK. Trigger the old checkout for this visitor.
case KameleoonError.Feature.environmentDisabled:
// The feature flag is disabled for the environment.
case KameleoonError.Feature.variableNotFound:
// Exception indicating that the requested variable has not been found. Check that the variable's key matches the one in your code.
default:
// Any other error.
}
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| featureKey | String | Identification key of the feature you want to retrieve. Este campo es obligatorio. |
| variableKey | String | Nombre de la variable cuyo valor desea obtener. Este campo es obligatorio. |
Valor de retorno
| Tipo | Descripción |
|---|
| Any | Datos asociados con este feature flag. The values can be Int, String, Bool or Dictionary (depending on the type defined on the web interface). |
Errores thrown
| Tipo | Descripción |
|---|
| KameleoonError.sdkNotReady | Exception indicating that the SDK is not fully initialized. |
| KameleoonError.Feature.notFound | Exception indicating that the requested feature ID has not been found in the SDK’s internal configuration. This exception usually means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed in the web-application). |
| KameleoonException.Feature.environmentDisabled | Exception indicating that the feature flag is disabled for the visitor’s current environment (for example, production, staging, or development). |
| KameleoonError.Feature.variableNotFound | Exception indicating that the requested variable wasn’t found. Check that the variable’s key in the Kameleoon app matches the key in your code. |
getFeatureVariationVariables()
- Use
getVariation() instead.
- This method was previously called
getFeatureAllVariables, which was removed in SDK version 4.0.0.
To retrieve all of the variables for a feature, call this method. You can modify your feature variables in the Kameleoon app.
Este método toma featureKey as an argument. It returns data with the [String: Any] type, as defined on the web interface. It will throw an exception (KameleoonError.Feature.notFound) if the requested feature has not been found in the SDK’s internal configuration.
let featureKey = "myFeature"
let variationKey = "on"
do {
allVariables = try kameleoonClient.getFeatureVariationVariables(featureKey: featureKey, variationKey: variationKey);
} catch KameleoonError.Feature.notFound {
// The feature is not activated in Kameleoon.
} catch KameleoonError.Feature.environmentDisabled {
// The feature flag is disabled for the environment.
} catch {
// This is a generic Exception handler that will handle all errors.
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| featureKey | String | Identification key of the feature you want to retrieve. Este campo es obligatorio. |
| variationKey | String | The key of the variation you want to retrieve. Este campo es obligatorio. |
Valor de retorno
| Tipo | Descripción |
|---|
| [String: Any] | Datos asociados con este feature flag. The values can be Int, String, Bool or Dictionary (depending on the type defined on the web interface). |
Errores thrown
| Tipo | Descripción |
|---|
| KameleoonError.sdkNotReady | Exception indicating that the SDK is not fully initialized. |
| KameleoonError.Feature.notFound | Exception indicating that the requested feature ID has not been found in the SDK’s internal configuration. This exception usually means that the feature flag has not been activated in the Kameleoon app (but code implementing the feature is already deployed in the web application). |
| KameleoonException.Feature.environmentDisabled | Exception indicating that the feature flag is disabled for the visitor’s current environment (for example, production, staging, or development). |
| KameleoonError.Feature.variationNotFound | Exception indicating that the requested variation key has not been found in the SDk’s internal configuration. This exception means that the feature flag has not yet been retrieved by the SDK, which may happen if the SDK is in polling mode. |
let featureKey = "myFeature"
let variationKey = "on"
do {
allVariables = try kameleoonClient.getFeatureVariationVariables(featureKey: featureKey, variationKey: variationKey);
} catch KameleoonError.Feature.notFound {
// The feature is not activated in Kameleoon.
} catch KameleoonError.Feature.environmentDisabled {
// The feature flag is disabled for the environment.
} catch {
// This is a generic Exception handler that will handle all errors.
}