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

Initialize SDK

This topic describes how to initialize the Optimizely Swift SDK in your application.

Use the start method to initialize the Swift SDK and instantiate an instance of the Optimizely client class that exposes API methods like Get Enabled Features. Each client corresponds to the datafile representing the state of a project for a certain environment.

Version

SDK v3.1.0

Description

The constructor accepts a configuration object to configure Optimizely.

Some parameters are optional because the SDK provides a default implementation, but you may want to override these for your production environments. For example, you may want override these to set up an error handler and logger to catch issues, an event dispatcher to manage network calls, and a User Profile Service to ensure sticky bucketing.

Parameters

The table below lists the required and optional parameters in Swift.

ParameterTypeDescription
sdkKey
required
StringSDK Key
logger
optional
OPTLoggerA custom logger
eventDispatcher
optional
OPTEventDispatcherA custom event handler
userProfileService
optional
OTPUserProfileServiceA custom user profile service
periodicDownloadInterval
optional
IntA custom interval for periodic background datafile download in seconds (default = 10 * 60 secs)
defaultLogLevel
optional
OptimizelyLogLevelLog level (default = OptimizelyLogLevel.info)

Returns

Instantiates an instance of the Optimzely class.

🚧

Note:

We currently support a single concurrent instance per SDK key

Examples

In our Swift SDK, you do not need to manage the datafile directly. The SDK includes a datafile manager that provides support for datafile polling to automatically update the datafile on a regular interval while the application is in the foreground.

To use it:

  1. Create a OptimizelyClient by supplying your SDK Key and optional configuration settings. You can find the SDK key in the Settings > Environments tab of a Full Stack project on the Optimizely Application.

  2. Choose whether to start the client synchronously or asynchronously and use the appropriate start method to instantiate a client.

// Build and config OptimizelyClient
optimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>")
        
// Synchronously initialize the client, then activate an experiment
do {
	try optimizely.start(datafile: datafileJSON)
  let variationKey = try optimizely.activate(experimentKey: experimentKey,
  																						userId: userId)        
} catch {
  // errors
}  

// Or, instantiate it asynchronously with a callback
optimizely.start { result in
	let variationKey = try? optimizely.activate(experimentKey: experimentKey,
  																						userId: userId)
}
// Build and config OptimizelyClient
self.optimizely = [[OptimizelyClient alloc] initWithSdkKey:@"<Your_SDK_Key>"];
    
// Synchronously initialize the client, then activate an experiment
BOOL status = [self.optimizely startWithDatafile:datafileJSON error:nil];
NSString *variationKey = [self.optimizely activateWithExperimentKey:experimentKey
                          userId:userId 
                          attributes:attributes 
                          error:nil];

// Or, instantiate it asynchronously with a callback
[self.optimizely startWithCompletion:^(NSData *data, NSError *error) {
	NSString *variationKey = [self.optimizely activateWithExperimentKey:experimentKey 
                          userId:userId
                          attributes:attributes
                          error:nil];
}];

See the Swift example: AppDelegate.swift. We also provide an Objective-C example: AppDelegate.m.

Use synchronous or asynchronous initialization

You have two choices for when to instantiate the Optimizely client: synchronous and asynchronous. The behavioral difference between the two methods is whether your application pings the Optimizely servers for a new datafile during initialization. The functional difference between the two methods is whether your app prioritizes accuracy or speed.

🚧

Important

You much decide to initialize the Swift SDK either synchronously or asynchronously. You cannot use both initialization methods.

Synchronous initialization

The synchronous method prioritizes speed over accuracy. Instead of attempting to download a new datafile every time you initialize an Optimizely client, your app uses a local version of the datafile. This local datafile can be cached from a previous network request.

When you initialize a client synchronously, the Optimizely manager first searches for a cached datafile. If one is available, the manager uses it to complete the client initialization. If the manager can't find a cached datafile, the manager searches for a bundled datafile. If the manager finds a the bundled datafile, it uses the datafile to complete the client initialization. If the manager can not find a bundled datafile, the manager can't initialize the client.

synchronous swift sdk intialization

To initialize an OptimizelyClient object synchronously, call optimizelyClient.start(datafile:datafile).

🚧

Important

The datafile you pass must have the same project ID that you provided when initializing the Optimizely manager.

Asynchronous initialization

The asynchronous method prioritizes accuracy over speed. During initialization, your app requests the newest datafile from the CDN servers. Requesting the newest datafile ensures that your app always uses the most current project settings, but it also means your app cannot instantiate a client until it downloads a new datafile, discovers the datafile has not changed, or until the request times out. This process takes time.

Initializing a client asynchronously executes like the synchronous initialization, except the manager will first attempt to download the newest datafile. This network activity is what causes an asynchronous initialization to take longer to complete.

If the network request returns an error (such as when network connectivity is unreliable) or if the manager discovers that the cached datafile is identical to the newest datafile, the manager then uses the synchronous approach. If manager discovers that the datafile has been updated and now differs from the cached datafile, the manager downloads the new datafile and uses it to initialize the client.

asynchronous swift sdk initialization

To initialize an OptimizelyClient object asynchronously, call optimizelyClient.start(completion:) and pass it a callback function.

🚧

Important

The datafile you pass must have the same project ID that you provided when initializing the Optimizely manager.

Configure datafile polling

During its initialization, the manager attempts to pull the newest datafile from the CDN servers. After this, the Optimizely manager can periodically check for and pull a new datafile at the time interval you set during its initialization. The process of checking for and downloading a new datafile is called datafile polling.

By default, datafile polling is disabled, so the client only checks for a new datafile during initialization. To enable polling, set a non-zero interval value. This value is the number of seconds the manager waits between datafile polling attempt.

// Datafile update interval can be configured when the SDK is configured
// Background datafile update is disabled if periodicDownloadInterval is zero
optimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>",
                              periodicDownloadInterval: 5*60)
// every 5 minutes
// Datafile update interval can be configured when the SDK is configured
// Background datafile update is disabled if periodicDownloadInterval is zero
self.optimizely = [[OptimizelyClient alloc] initWithSdkKey:@"<Your_SDK_Key>"
                    logger:nil
                    eventDispatcher:nil
                    userProfileService:nil
                    periodicDownloadInterval:5*60
                    defaultLogLevel:OptimizelyLogLevelInfo];

Usage notes

  • The minimum polling interval is 2 minutes while the app is open. If you specify shorter polling intervals than the minimum, the SDK will automatically reset the intervals to 2 minutes.
  • The Optimizely manager only checks for new datafiles when the SDK is active and the app is running on iOS/tvOS. You must configure background updates in iOS using the app delegate and calling the datafile manager download.
  • If you have datafile polling enabled, the Swift SDK automatically updates when a new datafile is detected to ensure that you are always working with the latest datafile. To be notified when the project has updated, register for a datafile change via the datafile change notification listener. The Swift demo app shows an example where we re-run our Is Feature Enabled method based on a new datafile.
  • If you wish to have your datafile just update when the app comes to foreground, you can do the following:
    1. Set the periodicDownloadInterval = 0
    2. Just call start when coming from foreground:
func applicationWillEnterForeground(_ application: UIApplication) {
        optimizely.start { result in
            switch result {
            case .failure(let error):
                print("Optimizely SDK initiliazation failed: \(error)")
            case .success:
                print("Optimizely SDK initialized successfully!")
              	// retest your features or experiments?
            }
						
            self.startWithRootViewController()
        }
    }

Enable bundled datafiles

When your customer opens your app for the first time after installing or updating it, the manager attempts to pull the newest datafile from Optimizely's CDN. If your app is unable to contact the servers, the manager can substitute a datafile that you included (bundled) when you created your app.

By bundling a datafile within your app, you ensure that the Optimizely manager can initialize without waiting for a response from the CDN. This lets you prevent poor network connectivity from causing your app to hang or crash while it loads.

Datafile bundling works with both synchronous and asynchronous initialization because reverting to a bundled datafile happens during the Optimizely manager's initialization, before a client is instantiated.

optimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>")

do {
	let localDatafilePath = Bundle.main.path(forResource: “datafileName”, ofType: "json")!
	let datafileJSON = try String(contentsOfFile: localDatafilePath, encoding: .utf8)
	try optimizely.start(datafile: datafileJSON)
	
	// Optimizely SDK initialized successfully
} catch {
	// Optimizely SDK initiliazation failed
}
self.optimizely = [[OptimizelyClient alloc] initWithSdkKey:@"<Your_SDK_Key>"];

NSString *filePath = [[NSBundle mainBundle] pathForResource:@“fileName” ofType:@"json"]
NSString *datafileJSON = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

BOOL status = [self.optimizely startWithDatafile:datafileJSON error:nil];

More Sample Code

// Here is sample code for synchronous and asynchronous SDK initializations with multiple options

// [Synchronous]
        
// [S1] Synchronous initialization
//      1. SDK is initialized instantly with a cached (or bundled) datafile
//      2. A new datafile can be downloaded in background and cached after the SDK is initialized.
//         The cached datafile will be used only when the SDK re-starts in the next session.

optimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>")
try? optimizely.start(datafile: localDatafile)
variationKey = try? optimizely.activate(experimentKey: "<Experiment_Key", userId: "<User_ID>")
        
// [S2] Synchronous initialization
//      1. SDK is initialized instantly with a cached (or bundled) datafile
//      2. A new datafile can be downloaded in background and cached after the SDK is initialized.
//         The cached datafile is used immediately to update the SDK project config.
        
optimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>")
try? optimizely.start(datafile: localDatafile,
                              doUpdateConfigOnNewDatafile: true)
variationKey = try? optimizely.activate(experimentKey: "<Experiment_Key", userId: "<User_ID>")
        
// [S3] Synchronous initialization
//      1. SDK is initialized instantly with a cached (or bundled) datafile
//      2. A new datafile can be downloaded in background and cached after the SDK is initialized.
//         The cached datafile is used immediately to update the SDK project config.
//      3. Polling datafile periodically.
//         The cached datafile is used immediately to update the SDK project config.
        
optimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>",
                                      periodicDownloadInterval: 60)
try? optimizely.start(datafile: localDatafile)
variationKey = try? optimizely.activate(experimentKey: "<Experiment_Key", userId: "<User_ID>")
        
// [Asynchronous]
        
// [A1] Asynchronous initialization
//      1. A datafile is downloaded from the server and the SDK is initialized with the datafile

optimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>")
optimizely.start { result in
variationKey = try? optimizely.activate(experimentKey: "<Experiment_Key", userId: "<User_ID>")
        }
        
// [A2] Asynchronous initialization
//      1. A datafile is downloaded from the server and the SDK is initialized with the datafile
//      2. Polling datafile periodically.
//         The cached datafile is used immediately to update the SDK project config.
        
optimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>",
                                      periodicDownloadInterval: 60)
optimizely.start { result in
variationKey = try? optimizely.activate(experimentKey: "<Experiment_Key", userId: "<User_ID>")
        }

Source files

The language/platform source files containing the implementation for Swift are at OptimizelyClient.swift.