Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

Optimizely will be sunsetting Full Stack Experimentation on July 29, 2024. See the recommended Feature Experimentation migration timeline and documentation.

Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideLegal TermsGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Run experiments

This topic provides sample code for running experiments using the Optimizely Objective-C SDK.

Once you have installed, initialized, and customized the Objective-C SDK for your implementation, you can run experiments and use our feature management and rollout functionality.

This topic is an addendum for specific 3.x topics in this guide by providing Objective-C SDK code samples and file links. Each section includes a link to the applicable 3.x topic for general information. Make sure that you are using to use the correct 3.1.0-beta code examples and resources when developing your implementation.

Use feature flags

// Evaluate a feature flag and a variable
bool enabled = [client isFeatureEnabled:@"price_filter" userId: userId];
int min_price = [[client getFeatureVariableInteger:@"price_filter" userId: userId] integerValue];
// Evaluate a feature flag and a variable
let enabled = optimizelyClient?.isFeatureEnabled("price_filter", userId: userId)
let min_price = optimizelyClient?.getFeatureVariableInteger("price_filter", "min_price", userId: userId)?.intValue

Define feature variables

- (DiscountAudience *)getDiscountAudience:(OPTLYManager *)manager {
    DiscountAudience *discountAudience = [[DiscountAudience alloc] init:@"general"];
    if ([manager getOptimizely]) {
        NSString *domain = @"";
        
        NSRange range = [self.userId rangeOfString:@"@"];
        if ( range.length > 0 ) {
            domain = [self.userId substringFromIndex:(range.location + range.length)];
        }
        NSString * audienceType = [[manager getOptimizely] getFeatureVariableString:@"discountAudienceFeatureKey" variableKey:@"discountAudienceFeatureVariableKey" userId:self.userId attributes:@{@"domainAttr": domain}];
        
        discountAudience = [[DiscountAudience alloc] init:audienceType];
    }
    
    return discountAudience;
}
// Look for getFeatureVariableString() in the following code.

// Sample usage
func discountAudience() -> DiscountAudience {
    var audience = DiscountAudience.general
    guard let userId = UserDefaults.user?.email,
        let _optimizelyClient = self.optimizelyClient
        else { return audience }

    let domain = userId.components(separatedBy: "@").last ?? ""
    let audienceType = _optimizelyClient.getFeatureVariableString(self.discountAudienceFeaturekey,
                                                          variableKey: self.discountAudienceFeatureVariableKey,
                                                          userId: userId,
                                                          attributes: [domainAttributeKey: domain])
    audience = DiscountAudience.init(fromString: audienceType ?? "")
    return audience
}

Run A/B tests

#import "OPTLYVariation.h"

// Activate an A/B test
OPTLYVariation *variation = [client activate:@"app_redesign" userId:userId];
if ([variation.variationKey isEqualToString:@"control"]) {
    // Execute code for "control" variation
} else if ([variation.variationKey isEqualToString:@"treatment"]) {
    // Execute code for "treatment" variation
} else {
    // Execute code for users who don't qualify for the experiment
}
// Activate an A/B test
let variation = client?.activate("app_redesign", userId:"12122")
if (variation?.variationKey == "control") {
// Execute code for "control" variation
} else if (variation?.variationKey == "treatment") {
// Execute code for "treatment" variation
} else {
// Execute code for users who don't qualify for the experiment
}

Assign variations with bucketing IDs

NSString *experimentKey = @"myExperiment";
NSString *userId = @"user123";
NSDictionary *attributes = @{@"device"              : @"iPhone",
                             @"ad_source"           : @"my_campaign",
                             @"$opt_bucketing_id"   : @"bucketingId123"};

// Activate with the bucketing ID
OPTLYVariation *variation = [optimizelyClient activate:experimentKey
                                                userId:user123
                                            attributes:attributes];

// Track with the bucketing ID
NSString *eventKey = @"myEvent";
[optimizelyClient track:eventKey
                        userId:userId
                    attributes:attributes];

// Get variation with the bucketing ID
OPTLYVariation *variation = [optimizelyClient activate:experimentKey
                                                userId:user123
                                            attributes:attributes];
let experimentKey = "myExperiment"
let userId = "user123"
let forcedVariationKey = "treatment"
let attributes = ["device"           : "iPhone",
                  "ad_source"        : "my_campaign",
                  "$opt_bucketing_id": "bucketingId123"]

// Activate with the bucketing ID
let variation = optimizelyClient?.activate(experimentKey, userId, attributes)

// Track with the bucketing ID
let eventKey = 'myConversion'
optimizelyClient?.track(eventKey, userId, attributes)

// Get variation with the bucketing ID
variation = optimizelyClient?.getVariation(experimentKey, userId, attributes)

Use forced bucketing

#import "OptimizelySDKiOS.h"

NSString *experimentKey = @"my_experiment";
NSString *userId = @"user123";
NSString *forcedVariationKey = @"treatment";

// Set a forced variation
[optimizelyClient setForcedVariation:experimentKey userId:userId variationKey:forcedVariationKey];

// Get a forced variation
OPTLYVariation *variation = [optimizelyClient getForcedVariation:experimentKey userId:userId];

// Clear a forced variation - set it to null!
[optimizelyClient setForcedVariation:experimentKey userId:userId variationKey:nil];
import OptimizelySDKiOS

let experimentKey = "my_experiment"
let userId = "user123"
let forcedVariationKey = "treatment"

// Set a forced variation
optimizelyClient?.setForcedVariation(experimentKey, userId: userId, variationKey: forcedVariationKey)

// Get a forced variation
let variation = optimizelyClient?.getForcedVariation(experimentKey, userId: userId)

// Clear a forced variation - set it to null!
optimizelyClient?.setForcedVariation(experimentKey, userId: userId, variationKey: nil)

Track events

// Track a conversion event for the provided user with attributes
[optimizely track:@"my_conversion"
           userId:@"user123"
       attributes:attributes];
// Track a conversion event for the provided user with attributes
optimizely?.track("my_conversion", userId:"user123", attributes:attributes)

Include event tags

NSDictionary *attributes = @{@"device" : @"iPhone", @"ad_source" : @"my_campaign"};

NSDictionary *eventTags = @{
  @"purchasePrice" : @64.32,
  @"category" : @"shoes",
  @"revenue": @6432  // reserved "revenue" tag
};

// Track event with user attributes and event tags
[optimizely track:@"my_conversion"
           userId:@"user123"
       attributes:attributes
       eventTags:eventTags];
let attributes = ["device" : "iPhone", "ad_source" : "my_campaign"]

var eventTags = Dictionary<String, Any>()
eventTags["purchasePrice"] = 64.32
eventTags["category"] = "shoes"
eventTags["revenue"] = 6432  // reserved "revenue" tag
eventTags["value"] = 4 // reserved "value" tag

// Track event with user attributes and event tags
optimizely?.track("my_conversion",
                  userId:"user123",
                  attributes:attributes,
                  eventTags:eventTags)

Manage bot filtering

/**
 * Get the user agent and pass it to the Optimizely client 
 *  as the attribute $opt_user_agent
 */

NSString *experimentKey = @"some_experiment";
NSString *userId = @"some_user";
NSDictionary *attributes = @{@"device"              : @"iphone",
                             @"location"            : @"Chicago",
                             @"$opt_user_agent"     : @"this_could_be_a_bot"};

// Include user agent when activating an A/B test
OPTLYVariation *variation = [optimizelyClient activate:experimentKey
                                                userId:userId
                                            attributes:attributes];

// Include user agent when tracking an event
NSString *eventKey = @"some_conversion_event";
[optimizelyClient track:eventKey
                        userId:userId
                    attributes:attributes];
/**
 * Get the user agent and pass it to the Optimizely client 
 *  as the attribute $opt_user_agent
 */

let experimentKey = "some_experiment"
let userId = "some_user"
let attributes = ["device"          : "iphone",
                  "location"        : "Chicago",
                  "$opt_user_agent" : "this_could_be_a_bot"]

// Include user agent when activating an A/B test
optimizelyClient?.activate(experimentKey, userId, attributes)

// Include user agent when tracking an event
let eventKey = 'some_conversion_event'
optimizelyClient?.track(eventKey, userId, attributes)

Access test and variation identifiers

For Objective-C, keys and IDs can be accessed on OPTLYExperiment objects using experimentKey and experimentId respectively. Likewise, keys and IDs can be accessed on OPTLYVariation objects using variationKey and variationId.

For Swift, keys and IDs can be accessed on OPTLYExperiment objects using experimentKey and experimentId respectively. Likewise, keys and IDs can be accessed on OPTLYVariation objects using variationKey and variationId.

Register notification listeners

// Add an Activate notification listener
NSInteger activateNotificationId = [optimizely.notificationCenter addDecisionNotificationListener:^(NSString * _Nonnull type, NSString * _Nonnull userId, NSDictionary<NSString *,id> * _Nullable attributes, NSDictionary<NSString *,id> * _Nonnull decisionInfo) {
    [logger logMessage:@"decision event" withLevel:OptimizelyLogLevelDebug];
}];

// Remove a sepcific listener
[optimizely.notificationCenter removeNotificationListener:activateNotificationId];

// Remove all of one type of listener
[optimizely.notificationCenter clearNotificationListeners:OPTLYNotificationTypeDecision];

// Remove all notification listeners
[optimizely.notificationCenter clearAllNotificationListeners];
// Add an activate notification listener
let activateNotificationId = optimizely?.notificationCenter?.addDecisionNotificationListener({ (type, userId, attributes, decisionInfo) in
    logger?.logMessage("decision event", with: OptimizelyLogLevel.debug)
})

// Remove a specific notification listener
optimizely?.notificationCenter?.removeNotificationListener(UInt(activateNotificationId!))

// Remove notification listeners of a certain type
optimizely?.notificationCenter?.clearNotificationListeners(OPTLYNotificationType.decision)

// Remove all notification listeners
optimizely?.notificationCenter?.clearAllNotificationListeners()

Set up Amplitude

#import "Amplitude.h"
#import "AMPIdentify.h"

[optimizely.notificationCenter addActivateNotificationListener:^(OPTLYExperiment *experiment, NSString *userId, NSDictionary<NSString *,NSString *> *attributes, OPTLYVariation *variation, NSDictionary<NSString *,NSString *> *event) {
  NSString *propertyKey
    = [NSString stringWithFormat:@"[Optimizely] %@",
       experiment.experimentKey];
  AMPIdentify *identify
    = [[AMPIdentify identify] set:propertyKey
       value:variation.variationKey];
  [[Amplitude instance] identify:identify];

  // Track impression event (optional)
  NSString *eventIdentifier
    = [NSString stringWithFormat:@"[Optimizely] %@ - %@",
       experiment.experimentKey,
       variation.variationKey];
  [[Amplitude instance] logEvent:eventIdentifier];
}];
import Amplitude_iOS
let activateNotificationId = optimizely?.notificationCenter?.addActivateNotificationListener({ (experiment, userId, attributes, variation, logEvent) in
  // Set "user property" for the user
  let propertyKey : String! = "[Optimizely] " + experiment.experimentKey
  let identify : AMPIdentify = AMPIdentify()
  identify.set(propertyKey, value:variation.variationKey as NSObject!)

  // Track impression event (optional)
  let eventIdentifier : String = "[Optimizely] "
  + experiment.experimentKey + " - " + variation.variationKey
  Amplitude.instance().logEvent(eventIdentifier)
})

Set up Google Analytics

See general topic: Set up Google Analytics.

If you're getting started, read the Google instructions for your platform:

🚧

Important

The Google Analytics iOS SDK does not support non-interaction events at this time. This may affect your bounce rate.

#import <Google/Analytics.h>

NSInteger activateNotificationId = [optimizely.notificationCenter addActivateNotificationListener:^(OPTLYExperiment *experiment, NSString *userId, NSDictionary<NSString *,NSString *> *attributes, OPTLYVariation *variation, NSDictionary<NSString *,NSString *> *event) {
    // Google Analytics tracker
    id<GAITracker> tracker = [GAI sharedInstance].defaultTracker;

    NSString *action
        = [NSString stringWithFormat:@"Experiment - %@",
            experiment.experimentKey];
    NSString *label
        = [NSString stringWithFormat:@"Variation - %@",
            variation.variationKey];
    [tracker send:[[GAIDictionaryBuilder
        createEventWithCategory:@"Optimizely"
                         action:action
                          label:label
                          value:nil] build]];
}];
// Add an activate notification listener
let activateNotificationId = optimizely?.notificationCenter?.addActivateNotificationListener({ (experiment, userId, attributes, variation, logEvent) in
    // Google Analytics tracker
    let tracker : GAITracker? = GAI.sharedInstance().defaultTracker

    let action : String = "Experiment - " + experiment.experimentKey
    let label : String = "Variation - " + variation.variationKey

    // Build and send an Event
    let builder = GAIDictionaryBuilder.createEvent(
        withCategory: "Optimizely",
        action: action,
        label: label,
        value: nil).build()
    tracker?.send(builder as [NSObject : AnyObject]!)
})

Set up Localytics

See general topic: Set up Localytics.

Objective-C

The example code has two parts:

  • Add a track event listener to wrap [Localytics tagEvent]
  • Add [optimizely track] to track conversions

Instead of calling [Localytics tagEvent] directly, wrap the calls with [optimizely track] to include bucketing information as event attributes.

The example code demonstrates how to add the track notification listener. Each [optimizely track] event tracking adds a mapping of experiment key to variation key to the event attributes and passes the mapping to [Localytics tagEvent].

The last step is to add [optimizely track] to track event conversions.

Consistent user identity

Maintaining a consistent user identity across multiple sessions and devices can help ensure proper reporting. Localytics provides some guidelines for their platform.

Optimizely recommends using the same user ID with these methods:

  • [optimizely activate]
  • [Localytics setCustomerId]

Alternative solution

Another solution is to set Localytics' Custom Dimensions using an activate notification listener. Custom dimensions can be used to segment users without needing to wrap [Localytics tagEvent], but they require configuration in the Localytics dashboard for each Optimizely test.

@import Localytics;

// Add a Track notification listener
NSInteger trackNotificationId = [optimizely.notificationCenter addTrackNotificationListener:^(NSString * _Nonnull eventKey, NSString * _Nonnull userId, NSDictionary<NSString *,NSString *> * _Nonnull attributes, NSDictionary * _Nonnull eventTags, NSDictionary<NSString *,NSObject *> * _Nonnull event) {
              // Tag custom event with attributes
              NSString *eventIdentifier
                  = [NSString stringWithFormat:@"[Optimizely] %@",
                      eventKey]];
              [Localytics tagEvent:eventIdentifier attributes:attributes];
          }];

// Track a conversion event for the provided user
[optimizely track:eventKey userId:userId];

Swift

The example code has two parts:

  • Add a track notification listener to wrap Localytics.tagEvent()
  • Add optimizely.track() to track conversions

Instead of calling Localytics.tagEvent() directly, wrap the calls with optimizely.track() to include bucketing information as event attributes.

The example code demonstrates how to add a track notification listener. Each time optimizely.track() event tracking adds a mapping of experiment key to variation key to the event attributes and pass the mapping to Localytics.tagEvent().

The last step is to add optimizely.track() to track event conversions.

Consistent user identity

Maintaining a consistent user identity across multiple sessions and devices can help ensure proper reporting. Localytics provides some guidelines for their platform.

Optimizely recommends using the same user ID with these methods:

  • optimizely.activate()
  • Localytics.setCustomerId()

Alternative solution

Another solution is to set Localytics' Custom Dimensions using an activate notification listener. Custom dimensions can be used to segment users without needing to wrap Localytics.tagEvent() but requires configuration in the Localytics dashboard for each Optimizely test.

import Localytics

// Add a track notification listener
optimizely?.notificationCenter?.addTrackNotificationListener({ (eventKey, userId, attributes, eventTags, event) in
  // Tag custom event with attributes
  let localyticsEventIdentifier : String = "[Optimizely] " + eventKey
  Localytics.tagEvent(localyticsEventIdentifier, attributes)
})

optimizely?.track(eventKey, userId)

Set up Mixpanel

Code example for Set up Mixpanel.

#import "Mixpanel/Mixpanel.h"

[optimizely.notificationCenter addActivateNotificationListener:^(OPTLYExperiment *experiment, NSString *userId, NSDictionary<NSString *,NSString *> *attributes, OPTLYVariation *variation, NSDictionary<NSString *,NSString *> *event) {
  // Mixpanel instance
  Mixpanel *mixpanel = [Mixpanel sharedInstance];

  NSString *propertyKey
    = [NSString stringWithFormat:@"[Optimizely] %@",
       experiment.experimentKey];
  [mixpanel
   registerSuperProperties:@{propertyKey: variation.variationKey}];

  // Set "People property" for the user
  [mixpanel.people set:@{propertyKey: variation.variationKey}];

  // Track impression event (optional)
  NSString *eventIdentifier
    = [NSString stringWithFormat:@"[Optimizely] %@ - %@",
       experiment.experimentKey,
       variation.variationKey];
  [mixpanel track:eventIdentifier];
}];
import Mixpanel

optimizely?.notificationCenter?.addActivateNotificationListener({ (experiment, userId, attributes, variation, logEvent) in
  // Mixpanel instance
  let mixpanel : MixpanelInstance = Mixpanel.mainInstance()

  // "Super property" will be sent with all future track calls
  let propertyKey : String! = "[Optimizely] " + experiment.experimentKey
  mixpanel.registerSuperProperties([propertyKey: variation.variationKey])

  // Set "People property" for the user
  mixpanel.people.set(property: propertyKey, to: variation.variationKey)

  // Track impression event (optional)
  let eventIdentifier : String = "[Optimizely] "
  + experiment.experimentKey + " - " + variation.variationKey
  mixpanel.track(event:eventIdentifier)
})

Next in the callback, we can optionally log an impression event that signifies that the Optimizely test was activated for the current user. You can use this event or another event you may already be tracking to calculate a conversion rate.

We recommend using the same user ID with the following methods:

LanguageActivate Callback
Objective-C- [optimizely activate]
- [mixpanel createAlias]
- [mixpanel identify]
Swift- optimizely.activate()
- mixpanel.createAlias()
- mixpanel.identify()

Compare results

When comparing Optimizely and Mixpanel results, remember to apply a date filter in Mixpanel to correspond with the dates your Optimizely test was running. People properties and super properties will remain set in Mixpanel even after your Optimizely test has stopped running.

Consistent user identity

Maintaining a consistent user identity across multiple sessions and devices can help ensure proper reporting. See Mixpanel documentation for guidelines for their platform.

Set up mParticle

See the general topic: Set up mParticle.

If you’re getting started, read the mParticle Getting Started guide for the iOS SDK.

Step 1: Prerequisites

  • Make sure that the required experiment is running correctly in Optimizely.
  • Install the mParticle SDK with the additional Optimizely kit on the iOS app.

Step 2: Enable the integration

The example code below sends a DECISION notification listener that contains information about the user, experiment, and variation to mParticle in an event called Experiment Viewed.

📘

Note

You can customize the event name and also specify which event tags are included the event payload.

@import mParticle_Apple_SDK;
 
// Conditionally activate an experiment for the provided user, can use mParticle ids 
OPTLYVariation *variation = [optimizely activate:@"my_experiment" 
                                          userId:[MParticle sharedInstance].identity.deviceApplicationStamp];
 
// mParticle event
MPProduct *product = [[MPProduct alloc] initWithName:@"Foo name"
                                                 sku:@"Foo sku"
                                            quantity:@4
                                               price:@100.00];
MPTransactionAttributes *attributes = [[MPTransactionAttributes alloc] init];
attributes.transactionId = @"foo-transaction-id";
// mapped to Optimizely as 45000 cents
attributes.revenue = @450.00;
attributes.tax = @30.00;
attributes.shipping = @30;
 
MPCommerceEventAction action = MPCommerceEventActionPurchase;
MPCommerceEvent *event = [[MPCommerceEvent alloc] initWithAction:action
                                                         product:product];
 
// mapped to Optimizely as a custom event name
[event addCustomFlag:@"custom revenue event name"
             withKey:MPKitOptimizelyEventName];
event.transactionAttributes = attributes;
[[MParticle sharedInstance] logCommerceEvent:event];
 
 
// DECISION notification listener that is bound to activate() and sends an event to mParticle with the experiment and variation information
 
[optimizely.notificationCenter addDecisionNotificationListener:^(NSString *type, NSString *userId, NSDictionary<NSString *,id> *attributes, NSDictionary<NSString *,id> *decisionInfo) {
     
	MPEvent *event = [[MPEvent alloc] initWithName:@"Experiment Viewed"
                                          type:MPEventTypeOther];
	 NSDictionary *eventInfo = @{
           @"experimentName" : decisionInfo[@"experimentKey"],
           @"variationName" : decisionInfo[@"variationKey"]
           };
      [[MParticle sharedInstance] logEvent:event eventInfo:eventInfo];
 
}];
import mParticle_Apple_SDK
 
// Optimizely DECISION notification listener for activate() 
let activateNotificationId = optimizely?.notificationCenter?.addDecisionNotificationListener { (type, userId, attributes, decisionInfo) in
        let eventInfo = ["experimentName": decisionInfo["experimentKey"] as Any,
                  "variationName": decisionInfo["variationKey"] as Any]
    
	   MParticle.sharedInstance().logEvent("Experiment Viewed", eventType: MPEventType.other, eventInfo: eventInfo)
 
}

Set up Segment

See Segment documentation for a semantic event that you can use to track A/B test variations for users.

In the example code below, we add an activate listener block callback to send Segment's A/B event.

#import <Analytics/SEGAnalytics.h>
[optimizely.notificationCenter addActivateNotificationListener:^(OPTLYExperiment *experiment, NSString *userId, NSDictionary<NSString *,NSString *> *attributes, OPTLYVariation *variation, NSDictionary<NSString *,NSString *> *event) {
       NSDictionary *properties = @{
           @"experimentId" : [experiment experimentId],
           @"experimentName" : [experiment experimentKey],
           @"variationId" : [variation variationId],
           @"variationName" : [variation variationKey]
           };
       [[SEGAnalytics sharedAnalytics] track:@"Experiment Viewed" properties:properties];
}];
import Analytics

let activateNotificationId = optimizely?.notificationCenter?.addActivateNotificationListener({ (experiment, userId, attributes, variation, logEvent) in
        let properties = ["experimentId": experiment.experimentId as Any,
                  "experimentName": experiment.experimentKey as Any,
                  "variationId": variation.variationId as Any,
                  "variationName": variation.variationKey as Any]
    
        SEGAnalytics.shared().track("Experiment Viewed", properties: properties)
})

API reference updates

This section provides updated Objective-C SDK code examples for all Optimizely methods.

Source files containing the implementations are at Optimizely.h.

Instantiate

Parameter names

datafile
errorHandler
eventDispatcher
logger
userProfileService
clientVersion
clientEngine
datafile
errorHandler
eventDispatcher
logger
userProfileService
clientVersion
clientEngine

Code example

let optimizelyClient: OPTLYClient? = optimizelyManager?.initialize(withDatafile:jsonDatafile!)

Activate

Parameter names

NSDictionary *attributes = @{
  @"device": @"iPhone",
  @"lifetime": @24738388,
  @"is_logged_in": @true
};

NSString *variationKey = [optimizely activateWithExperimentKey: @"my_experiment_key"
                          userId:@"user_123"
                          attributes:attributes
                          error:nil];
let attributes = [
  "device": "iPhone",
  "lifetime": 24738388,
  "is_logged_in": true,
]

let variationKey = try? optimizely.activate(experimentKey:"my_experiment_key",
                                            userId: "user_123",
                                            attributes: attributes)

Returns

@return The key of the variation where the user is bucketed, or `nil` if the user doesn't qualify for the experiment.
@return The key of the variation where the user is bucketed, or `nil` if the user doesn't qualify for the experiment.

Code example

NSDictionary *attributes = @{
  @"device": @"iPhone",
  @"lifetime": @24738388,
  @"is_logged_in": @true
};

OPTLYVariation *variation = [optimizelyClient activate:@"my_experiment_key",
                                                userId:@"user_123",
                                            attributes:attributes];
let attributes = [
  "device": "iPhone",
  "lifetime": 24738388,
  "is_logged_in": true,
]

let variation = optimizelyClient?.activate("my_experiment_key", userId:"user_123", attributes:attributes)

Get Enabled Features

Parameter names

userId
attributes
userId
attributes

Returns

@return A list of keys corresponding to the features that are enabled for the user, or an empty list if no features could be found for the specified user.
@return NSArray<NSString> A list of keys corresponding to the features that are enabled for the user, or an empty list if no features could be found for the specified user.

Code example

NSDictionary *attributes = @{
  @"device": @"iPhone",
  @"lifetime": @24738388,
  @"is_logged_in": @true
};

NSArray<NSString *> *enabledFeatures = [optimizelyClient getEnabledFeatures:@"user_123"
                                                                 attributes:attributes];
let attributes = [
  "device": "iPhone",
  "lifetime": 24738388,
  "is_logged_in": true,
]

let enabledFeatures = optimizelyClient?.getEnabledFeatures("user_123", attributes:attributes)

Get Feature Variable

Boolean

Returns the value of the specified Boolean variable.

- (NSNumber *)getFeatureVariableBoolean:(nullable NSString *)featureKey
                      variableKey:(nullable NSString *)variableKey
                           userId:(nullable NSString *)userId
                       attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes;
- (NSNumber *)getFeatureVariableBoolean:(nullable NSString *)featureKey
                      variableKey:(nullable NSString *)variableKey
                           userId:(nullable NSString *)userId
                       attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes

Double

Returns the value of the specified double variable.

- (NSNumber *)getFeatureVariableDouble:(nullable NSString *)featureKey
                       variableKey:(nullable NSString *)variableKey
                            userId:(nullable NSString *)userId
                        attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes;
- (NSNumber *)getFeatureVariableDouble:(nullable NSString *)featureKey
                       variableKey:(nullable NSString *)variableKey
                            userId:(nullable NSString *)userId
                        attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes;

Integer

Returns the value of the specified integer variable.

- (NSNumber *)getFeatureVariableInteger:(nullable NSString *)featureKey
                     variableKey:(nullable NSString *)variableKey
                          userId:(nullable NSString *)userId
                      attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes;
- (NSNumber *)getFeatureVariableInteger:(nullable NSString *)featureKey
                     variableKey:(nullable NSString *)variableKey
                          userId:(nullable NSString *)userId
                      attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes;

String

Returns the value of the specified string variable.

- (NSString *_Nullable)getFeatureVariableString:(nullable NSString *)featureKey
                           variableKey:(nullable NSString *)variableKey
                                userId:(nullable NSString *)userId
                            attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes;
- (NSString *_Nullable)getFeatureVariableString:(nullable NSString *)featureKey
                           variableKey:(nullable NSString *)variableKey
                                userId:(nullable NSString *)userId
                            attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes;

Parameter names

featureKey
variableKey
userId
attributes
featureKey
variableKey
userId
attributes

Returns

@return The value of the variable, or `nil` if the feature key is invalid, the variable key is invalid, or there is a mismatch with the type of the variable.
experimentKey
userId
attributes

Code example

NSDictionary *attributes = @{
  @"device": @"iPhone",
  @"lifetime": @24738388,
  @"is_logged_in": @true
};

NSNumber *featureVariableValue = [optimizelyClient getFeatureVariableDouble:@"my_feature_key",
                                                                variableKey:@"double_variable_key",
                                                                     userId:@"user_123",
                                                                 attributes:attributes];
let attributes = [
  "device": "iPhone",
  "lifetime": 24738388,
  "is_logged_in": true,
]

let featureVariableValue = optimizelyClient?.getFeatureVariableDouble("my_feature_key", variableKey:"double_variable_key", userId:"user_123", attributes:attributes)

Get Forced Variation

Parameter names

experimentKey
userId
experimentKey
userId

Returns

@return The variation the user was bucketed into, or `null` if `setForcedVariation` failed to force the user into the variation.
@return forced variation if it exists, otherwise return nil.

Code example

let variation = optimizelyClient?.getForcedVariation(”my_experiment_key”, userId:”user_123”);
let attributes = [
  "device": "iPhone",
  "lifetime": 24738388,
  "is_logged_in": true,
]

let variation = optimizelyClient?.activate("my_experiment_key", userId:"user_123", attributes:attributes)

Get Variation

Parameter names

experimentKey
userId
attributes
experimentKey
userId
attributes

Returns

@return The variation into which the user is bucketed. This value can be nil.
@return The variation into which the user was bucketed. This value can be nil.

Code example

NSDictionary *attributes = @{
  @"device": @"iPhone",
  @"lifetime": @24738388,
  @"is_logged_in": @true
};

OPTLYVariation *variation = [optimizelyClient variation:@"my_experiment_key",
                                                 userId:@"user_123",
                                             attributes:attributes];
let attributes = [
  "device": "iPhone",
  "lifetime": 24738388,
  "is_logged_in": true,
]

let variation = optimizelyClient?.variation("my_experiment_key", userId:"user_123", attributes:attributes)

Is Feature Enabled

Parameter names

featureKey
userId
attributes
featureKey
userId
attributes

Returns

@return YES if feature is enabled, false otherwise.
@return YES if feature is enabled, false otherwise.

Code example

NSDictionary *attributes = @{
  @"device": @"iPhone",
  @"lifetime": @24738388,
  @"is_logged_in": @true
};

bool enabled = [optimizelyClient isFeatureEnabled:@"my_feature_key",
                                           userId:@"user_123",
                                       attributes:attributes];
let attributes = [
  "device": "iPhone",
  "lifetime": 24738388,
  "is_logged_in": true,
]

let enabled = optimizelyClient?.isFeatureEnabled("my_feature_key", userId:"user_123", attributes:attributes)

Set Forced Variation

Parameter names

experimentKey
userId
variationKey
experiment_key
user_id
variation_key

Returns

@return `YES` if the user was successfully forced into a variation, `NO` if the `experimentKey` isn't in the project file or the `variationKey` isn't in the experiment.
@return A boolean value that indicates if the set completed successfully.

Code example

[optimizelyClient setForcedVariation:@"my_experiment_key"
                              userId:@"user_123"
                        variationKey:@"some_variation_key"];
optimizelyClient?.setForcedVariation(”my_experiment_key”, userId:”user_123”, variationKey:"some_variation_key");

Track

Parameter names

eventKey
userId
attributes
eventTags
eventKey
userId
attributes
eventTags

Returns

This method sends conversion data to Optimizely. It doesn't provide return values.

Code example

NSDictionary *attributes = @{
  @"device": @"iPhone",
  @"lifetime": @24738388,
  @"is_logged_in": @true
};

NSDictionary *tags = @{
  @"category" : @"shoes",
  @"count": @5
};

[optimizelyClient track:@"my_event_key"
                 userId:@"user_123"
             attributes:attributes
              eventTags:tags];
let attributes = [
  "device": "iPhone",
  "lifetime": 24738388,
  "is_logged_in": true,
]

let tags = [
  "category": "shoes",
  "count": 2,
]

optimizelyClient?.track("my_event_key", userId:"user_123", attributes:attributes, eventTags:tags);