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 iOSPrerequisites
- 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 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:Configuración adicional
To customize the SDK’s behavior, create akameleoon-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) | Define con qué frecuencia el SDK envía un evento de actividad para prolongar la sesión del visitante. Cambiarlo puede tener efectos secundarios — consulte esta sección antes de ajustarlo. El valor mínimo y por defecto es 60 000 ms; cualquier valor menor distinto de cero se ignora y se aplica el valor por defecto. Establézcalo en 0 para desactivar el tracking periódico de actividad; en ese caso, se envía un único evento de actividad al inicio. | 60 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 ayuda a reducir el uso de red y el consumo de batería al controlar con qué frecuencia el SDK envía un evento de actividad para prolongar la sesión del visitante en la Data API. El valor por defecto y el valor mínimo permitido es 60 000 ms (60 segundos); cualquier valor menor distinto de cero se ignora y se aplica el valor por defecto. Los temporizadores se pausan cuando la aplicación está en segundo plano, por lo que el intervalo solo avanza efectivamente mientras la aplicación está en primer plano.
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.
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.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.
Best practices for initialization and usage
- Initializing
KameleoonClientas 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 therunWhenReadymethod. 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.
- Swift
- Swift (Async)
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étodogetVariation() 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étodoaddData() 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étodotrackConversion() 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étodogetRemoteVisitorData() 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.
- Swift
- Swift (Async)
Device A
Device B
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, utiliceCustomData 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 passedisUniqueIdentifier=truetoKameleoonClientConfig- to retrieve data for all linked visitors.trackConversion()orflush()with passedisUniqueIdentifier=truetoKameleoonClientConfig- to track some data for specific visitor that is associated with another visitor.
- Swift
- Swift (Async)
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.
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:- 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 objetoCustomData. Aquí,newVisitorCodehace referencia al identificador que desea usar para el bucketing (por ejemplo, el nuevouserIdoaccountId).
- 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 estenewVisitorCode(su clave personalizada) en lugar delvisitorCodepredeterminado. Usar elnewVisitorCodesignifica 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 elvisitorCodeoriginal. 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.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.
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+)
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 enKameleoonClientFactory. 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á.
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 therunWhenReady() method with a callback.
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)
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.
- Swift
- Swift (Async)
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. |
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.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.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)
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.
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)
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
onlyActivese establece entrue, el métodogetVariations()devolverá las variaciones de los feature flags siempre que el usuario no esté asignado a la variaciónoff. - El parámetro
trackcontrola si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set totrue. Si se establece enfalse, el seguimiento estará deshabilitado.
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.
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 specificVariation 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.
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
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.
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.Valor de retorno
| Tipo | Descripción |
|---|---|
[String] | List of feature flag keys |
getDataFile()
Devuelve la configuración actual del SDK como un objetoDataFile.
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
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.
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’).Events
updateConfigurationHandler()
El métodoupdateConfigurationHandler() 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.
Este handler solo se activa cuando el SDK está en modo streaming (server-sent events). No se llama para actualizaciones de configuración realizadas en el modo polling por defecto (
refreshIntervalMinute).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.Valor de retorno
| Tipo | Descripción |
|---|---|
String | String representing a unique visitor code used in SDK. |
addData()
El métodoaddData() 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.
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
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.
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.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.
- Swift
- Swift (Async)
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. |
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.
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.- Swift
- Swift (Async)
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. |
Using parameters with RemoteVisitorDataFilter
El métodogetRemoteVisitorData() 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
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.
- Swift
- Swift (Async)
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. |
setLegalConsent()
You must use this method to specify whether the visitor has given legal consent to use their personal data. Setting thelegalConsent 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. |
Tipos de datos
This section lists the data types supported by Kameleoon. Several standard data types are provided, as well as theCustomData type for defining custom data types.
Conversion
El conjunto de datosConversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
| 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. | [] |
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
CustomDatafor each uniqueindex. Adding anotherCustomDatawith the sameindexwill replace the existingCustomData. - The custom data
indexcan 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
CustomDatainstance 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.
Device
Since iOS SDK
4.14.0, the Device is automatically detected based on the value of UIDevice.current.userInterfaceIdiom. However, you can still manually override it if needed.| Nombre | Tipo | Descripción |
|---|---|---|
| device | Device | List of devices: phone, tablet, desktop. Este campo es obligatorio. |
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. |
Returned Types
DataFile
ElDataFile 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. |
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 |
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. |
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
Variationobject provides details about the assigned variation and its associated experiment, while theVariableobject contains specific details about each variable within a variation. - Ensure that your code handles the case where
idorexperimentIdmay be-1, indicating a default variation. - The
variablesmap might be empty if no variables are associated with the variation.
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). |
Deprecated methods
getFeatureVariationKey()
- 📨 Envía datos de seguimiento a Kameleoon
Use
getVariation() instead.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.
getActiveFeatureList()
Use
getVariations() instead.Valor de retorno
| Tipo | Descripción |
|---|---|
| [String] | List of feature flag keys which are active for the visitor |
getActiveFeatures()
Use
getVariations() instead.getActiveFeatures method retrieves information about the active feature flags that are available for the specified visitor code.
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 version4.0.0.
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.
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 version4.0.0.
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.
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. |