• SDKS
No results for ""


iOS (Swift) SDK reference

Read time: 9 minutes
Last edited: Jul 08, 2020
iOS Client SDK for Swift

This documentation is for the LaunchDarkly SDK for Swift iOS versions 4.0.0 and later.

Earlier versions of the SDK support Objective-C.

This reference guide documents all of the methods available in our iOS SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source. To learn more, read iOS SDK GitHub repository. Additionally you can clone and run sample applications using this SDK with iOS, macOS, and tvOS.

Getting started

Building on top of our Getting Started guide guide, the following steps will get you started with using the LaunchDarkly SDK in your iOS application.

The first step is to install the LaunchDarkly SDK as a dependency in your application. LaunchDarkly supports multiple methods for installing the SDK in your application.

If you're using CocoaPods, you can install the SDK by adding the following to your Podfile. Refer to the SDK releases page to identify the latest version.

2target 'YourTargetName' do
3 pod 'LaunchDarkly', '4.7.0'

Then, run pod install from the project directory that contains the podfile:

1pod install

If you're using Carthage, you can install the SDK by specifying it in your Cartfile. Again, refer to the SDK releases page to identify the latest version.

1github "launchdarkly/ios-client" "4.7.0"

Then run carthage update to build the framework. Optionally, specify the --platform option to build only the frameworks that support your platform(s). Drag the built Darkly.framework from your platform's Carthage/Build folder into your Xcode project. Follow the instructions at Getting Started to finish the setup. Your app may not build until you add the run script phase to copy-frameworks to your target(s).

Refer to the SDK readme for instructions on installing the SDK without CocoaPods or Carthage.

Next you should import the LaunchDarkly client in your application code.

1import LaunchDarkly

Once the SDK is installed and imported, you'll want to create a single, shared instance of LDClient. You should specify your mobile key here so that your application will be authorized to connect to LaunchDarkly and for your application and environment.

1let config = LDConfig(mobileKey: "YOUR_MOBILE_KEY")
3let user = LDUser(key: "test-user")
5LDClient.shared.start(config: config, user: user)
7// If you need feature flags to load before continuing, use the
8// startCompleteWhenFlagsReceived method with a completion.
9LDClient.shared.startCompleteWhenFlagsReceived(config: config, user: user) {
10 NSLog("Flags ready!")
13// Add the startWaitSeconds parameter if you want to limit the
14// maximum time to wait for flags to be received before calling the completion closure.
15// This parameter is only available in versions 4.7.0 and later.
16LDClient.shared.startCompleteWhenFlagsReceived(config: config, user: user, startWaitSeconds: 5) {
17 NSLog("Flags ready!")
Mobile Keys

Be sure to use a mobile key from your Environments page. Never embed a server-side SDK key into a mobile application.

Using LDClient, you can check which variation a particular user should receive for a given feature flag.

1let boolFeatureFlagValue = LDClient.shared.variation(forKey: "bool-flag-key", fallback: false)
3if boolFeatureFlagValue {
4 // application code to show the feature
5else {
6 // the code to run if the feature is off

Lastly, when your application is about to terminate, shut down LDClient. This ensures that the client releases any resources it is using, and that any pending analytics events are delivered to LaunchDarkly. If your application quits without this shutdown step, you may not see your requests and users on the dashboard, because they are derived from analytics events. This is something you only need to do once.


Client Configuration Options

Here is a complete client configuration object utilizing all available fields:

1var ldConfig = LDConfig(mobileKey: safeKey)
2/// The default url for making feature flag requests
3ldConfig.baseUrl = URL(string: "https://app.launchdarkly.com")!
4/// The default url for making event reports
5ldConfig.eventsUrl = URL(string: "https://mobile.launchdarkly.com")!
6/// The default url for connecting to the *clientstream*
7ldConfig.streamUrl = URL(string: "https://clientstream.launchdarkly.com")!
8/// The default maximum number of events the LDClient can store
9ldConfig.eventCapacity = 100
10/// The default maximum number of events the LDClient can store
11ldConfig.connectionTimeout: TimeInterval = 10.0
12/// The default time interval between event reports. (30 seconds)
13ldConfig.eventFlushInterval: TimeInterval = 30.0
14/// The default time interval between feature flag requests. Used only for polling mode. (5 minutes)
15ldConfig.flagPollingInterval: TimeInterval = 300.0
16/// The default interval between feature flag requests while running in the background. Used only for polling mode. (60 minutes)
17ldConfig.backgroundFlagPollingInterval: TimeInterval = 3600.0
18/// The default streaming mode (streaming)
19ldConfig.streamingMode = LDStreamingMode.streaming
20/// The default mode for enabling background flag requests. (false)
21ldConfig.enableBackgroundUpdates = false
22/// The default mode to set LDClient online on a start call. (true)
23ldConfig.startOnline = true
24/// The default setting for private user attributes. (false)
25ldConfig.allUserAttributesPrivate = false
26/// The default private user attribute list (nil)
27ldConfig.privateUserAttributes: [String]? = nil
28/// The default HTTP request method for `clientstream` connection and feature flag requests. When true, these requests will use the non-standard verb `REPORT`. When false, these requests will use the standard verb `GET`. (false)
29ldConfig.useReport = false
30/// The default setting controlling the amount of user data sent in events. When true the SDK will generate events using the full LDUser, excluding private attributes. When false the SDK will generate events using only the LDUser.key. (false)
31ldConfig.inlineUserInEvents = false
32/// The default setting controlling information logged to the console, and modifying some setting ranges to facilitate debugging. (false)
33ldConfig.debugMode = false
34/// The default setting for whether we request evaluation reasons for all flags.
35ldConfig.evaluationReasons = false
36/// The default setting for the maximum number of locally cached users. Set to -1 to cache an unlimited number of users.
37ldConfig.maxCachedUsers = 5

User Configuration Options

Here is a complete user configuration object utilizing all available fields:

1var user = LDUser()
2///Client app defined string that uniquely identifies the user. If the client app does not define a key, the SDK will assign an identifier associated with the anonymous user. The key cannot be made private.
3user.key: String
4///Client app defined name for the user. (Default: nil)
5user.name: String?
6///Client app defined first name for the user. (Default: nil)
7user.firstName: String?
8///Client app defined last name for the user. (Default: nil)
9user.lastName: String?
10///Client app defined country for the user. (Default: nil)
11user.country: String?
12///Client app defined ipAddress for the user. (Default: nil)
13user.ipAddress: String?
14///Client app defined email address for the user. (Default: nil)
15user.email: String?
16///Client app defined avatar for the user. (Default: nil)
17user.avatar: String?
18///Client app defined dictionary for the user. The client app may declare top level dictionary items as private. If the client app defines custom as private, the SDK considers the dictionary private except for device & operatingSystem (which cannot be made private). See `privateAttributes` for details. (Default: nil)
19user.custom: [String: Any]?
20///Client app defined isAnonymous for the user. If the client app does not define isAnonymous, the SDK will use the `key` to set this attribute. isAnonymous cannot be made private. (Default: true)
21user.isAnonymous: Bool
22///Client app defined device for the user. The SDK will determine the device automatically, however the client app can override the value. The SDK will insert the device into the `custom` dictionary. The device cannot be made private. (Default: the system identified device)
23user.device: String?
24///Client app defined operatingSystem for the user. The SDK will determine the operatingSystem automatically, however the client app can override the value. The SDK will insert the operatingSystem into the `custom` dictionary. The operatingSystem cannot be made private. (Default: the system identified operating system)
25user.operatingSystem: String?
27Client app defined privateAttributes for the user.
28The SDK will not include private attribute values in analytics events, but private attribute names will be sent.
29This attribute is ignored if `LDConfig.allUserAttributesPrivate` is true. Combined with `LDConfig.privateUserAttributes`. (Default: nil)
31user.privateAttributes: [String]?

Private User Attributes

You can optionally configure the iOS SDK to treat some or all user attributes as private user attributes. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

In the iOS SDK there are two ways to define private attributes for the entire LaunchDarkly client:

  • When creating the LDConfig object, you can set the allUserAttributesPrivate attribute to true.

  • When creating the LDConfig object, you can set the privateUserAttributes attribute to a list of user attribute names, such as @[@"name", @"email"];. If any user has a custom or built-in attribute named in this list, it will be removed before the user is sent to LaunchDarkly.

You can also mark attributes as private when building the user object itself by calling the equivalent “private” user builder method. For example:

1var user = LDUser()
3user.name = "private_citizen"
4user.privateAttributes = ["name"]

Anonymous Users

You can also distinguish logged-in users from anonymous users in the SDK, as follows:

1var user = LDUser()
3user.name = "anonymous_citizen"
4user.isAnonymous = true

You will still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. You also can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. This is actually a good thing, because it keeps anonymous users from polluting your Users page!


The variation method determines whether a flag is enabled or not for a specific user. In the V4 SDK, there is a single variation method for all types using Swift, however Objective-C requires type specific methods:

1let boolFeatureFlagValue = LDClient.shared.variation(forKey: "bool-flag-key", fallback: false)
3let dictionaryFlagValue = LDClient.shared.variation(forKey: "dictionary-key", fallback: ["a": 1, "b": 2] as [LDFlagKey: Any])

The variation method returns the variation for the given feature flag. If the flag does not exist, cannot be cast to the correct return type, or the LDClient is not started, the method returns the fallback value. Use this method when the fallback value is a non-Optional type. See variation with the Optional return value when the fallback value can be nil. A variation is a specific flag value. For example a boolean feature flag has 2 variations, true and false. You can create feature flags with more than 2 variations using other feature flag types. See LDFlagValue for the available types. The LDClient must be started in order to return feature flag values. If the LDClient is not started, it will always return the fallback value. The LDClient must be online to keep the feature flag values up-to-date.

When online, the LDClient has two modes for maintaining feature flag values: streaming and polling. The client app requests the mode by setting the config.streamingMode, see LDConfig for details.

In streaming mode, the LDClient opens a long-running connection to LaunchDarkly's streaming server (called clientstream). When a flag value changes on the server, the clientstream notifies the SDK to update the value. Streaming mode is not available on watchOS. On iOS and tvOS, the client app must be running in the foreground to connect to clientstream. On macOS the client app may run in either foreground or background to connect to clientstream. If streaming mode is not available, the SDK reverts to polling mode.

In polling mode, the LDClient requests feature flags from LaunchDarkly's app server at regular intervals defined in the LDConfig. When a flag value changes on the server, the LDClient will learn of the change the next time the SDK requests feature flags.

When offline, LDClient closes the clientstream connection and no longer requests feature flags. The LDClient will return feature flag values (assuming the LDClient was started), which may not match the values set on the LaunchDarkly server.

A call to variation records events reported later. Recorded events allow clients to analyze usage and assist in debugging issues.

Handling flag values on initial application launch

When LDClient is initialized for the first time at app launch, users will receive feature flag fallback values until an initial connection to LaunchDarkly is completed for the first time. Take a look at the section above on various ways to initialize the client.


This has been available since v4.3.0.

The variationDetail methods work the same as variation, but also provide additional reason information about how a flag value was calculated (for instance, if the user matched a specific rule). You can examine the reason data programmatically; you can also view it with data export, if you are capturing detailed analytics events for this flag.

To learn more, read Evaluation reasons.

All Flags

Creating Users

Unlike variation and identify calls, allFlags does not send events to LaunchDarkly. Users tracked by allFlags are not created or updated in the LaunchDarkly dashboard.

Returns a dictionary with the flag keys and their values. If the LDClient is not started, returns nil. The dictionary will not contain feature flags from the server with null values. LDClient will not provide any source or change information, only flag keys and flag values. The client app should convert the feature flag value into the desired type.

1let allFlags = LDClient.shared.allFlagValues

Tracking Events

Adds a custom event to the LDClient event store. A client app can set a tracking event to allow client customized data analysis. Once an app has called trackEvent, the app cannot remove the event from the event store. LDClient periodically transmits events to LaunchDarkly based on the frequency set in LDConfig.eventFlushInterval. The LDClient must be started and online. The SDK stores events tracked while the LDClient is offline, but started.

Once the SDK's event store is full, the SDK discards events until they can be reported to LaunchDarkly. Configure the size of the event store using eventCapacity on the config. The first parameter key: is the key for the event. The SDK does nothing with the key, which can be any string the client app sends. The second parameter data: is the data for the event and is optional. The SDK does nothing with the data, which can be any valid JSON item the client app sends. The method throws JSONSerialization.JSONError.invalidJsonObject if the data is not a valid JSON item.

Experimentation metric values
This has been available since v4.3.0.

You can now optionally add a metricValue parameter of type Double to track in Swift or as a required paramter to the overloaded track method in Objective-C.

1let data = ["some-custom-key": "some-custom-value", "another-custom-key": 7]
2LDClient.shared.trackEvent(key: "MY_TRACK_EVENT_NAME", data: data)

Offline Mode

In some situations, you might want to stop making remote calls to LaunchDarkly and switch to the last known values for your feature flags. Offline mode lets you do this easily. The SDK protects itself from multiple rapid calls to setOnline(true) by enforcing an increasing delay (called throttling) each time setOnline(true) is called within a short time. The first time, the call proceeds normally. For each subsequent call the delay is enforced, and if waiting, increased to a maximum delay. When the delay has elapsed, the setOnline(true) will proceed, assuming that the client app has not called setOnline(false) during the delay. Therefore a call to setOnline(true) may not immediately result in the LDClient going online. Client app developers should consider this situation abnormal, and take steps to prevent the client app from making multiple rapid setOnline(true) calls. Calls to setOnline(false) are not throttled. Note that calls to start(config: user: completion:), and setting the config or user can also call setOnline(true) under certain conditions. After the delay, the SDK resets and the client app can make a subsequent call to setOnline(true) without being throttled.

Client apps can set a completion closure called when the setOnline call completes. For unthrottled setOnline(true) and all setOnline(false) calls, the SDK will call the closure immediately on completion of this method. For throttled setOnline(true) calls, the SDK will call the closure after the throttling delay at the completion of the setOnline method.

The SDK will not go online if the client has not been started, or the mobileKey is empty. For macOS, the SDK will not go online in the background unless enableBackgroundUpdates is true.

Use isOnline to get the online/offline state.

2LDClient.shared.setOnline(true) {
3 return true
5let connectionStatus = LDClient.shared.isOnline
Lack of network connectivity

If a user's device is in airplane/flight mode or if they are not connected to a network, LaunchDarkly will use the latest stored flag settings in memory. If there are no previously stored flag settings, then the fallback values will be used.

Reporting Events

Internally, the LaunchDarkly SDK keeps an event buffer for trackEvent calls. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK in a simulator), you may want to manually call reportEvents to process events immediately.


Changing the user context

This has been available since version 4.2.0.

If your app is used by multiple users on a single device, you may want to change users and have separate flag settings for each user. To achieve this, the SDK will store the last 5 user contexts on a single device, with support for switching between different user contexts. When a new user is set, the LDClient goes offline and sets the new user. If the client was online when the new user was set, it goes online again, subject to a throttling delay if in force. To change both the config and user, set the LDClient offline, set both properties, then set the LDClient online. Setting user is now deprecated, please use the identify method instead. This method allows you to set a completion and you no longer need to manually set LDClient online. Client apps should follow the Apple Privacy Policy when collecting user information. If the client app does not create a LDUser, LDClient creates an anonymous default user, which can affect the feature flags delivered to the LDClient.

You can use the identify method to switch user contexts:

1// Usage as of 4.2.0
2var newUser = LDUser()
3newUser.key = "MY_NEW_USER_KEY"
4LDClient.shared.identify(user: newUser)
5//identify can also be called with a completion
6LDClient.shared.identify(user: newUser) {
7 NSLog("User updated!")
10// Usage in versions prior to 4.2.0 (now deprecrated)
11var newUser = LDUser()
12newUser.key = "MY_NEW_USER_KEY"
13LDClient.shared.user = newUser

Real-time updates

LaunchDarkly manages all flags for a user context in real-time by updating flags based on a real-time event stream. When a flag is modified from the LaunchDarkly dashboard, the flag values for the current user will update almost immediately.

To accomplish real-time updates, LaunchDarkly broadcasts an event stream that is listened to by the V4 SDK. Whenever an event is performed on the dashboard, the V4 SDK is notified of the updated flag settings in real-time.

The SDK provides methods for listening to a single flag, all the flags, or a lack of change to any flags. observeFlagsUnchanged is called when the SDK successfully receives an update or comes back online but no flags have changed. If the value of the flag changes, the method executes the handler, passing in the changedFlag containing the old and new flag values, and old and new flag value source. The SDK retains only weak references to the owner, which allows the client app to freely destroy owners without issues. Client apps should use a capture list specifying [weak self] inside handlers to avoid retain cycles causing a memory leak. The SDK executes handlers on the main thread. LDChangedFlag does not know the type of oldValue or newValue. The client app should cast the value into the type needed.

LDObserverOwner Lifecycle

The lifetime of the LDObserverOwner must extend for at least as long as you wish to receive flag change notifications.

1let flagKey = "MY_OBSERVE_FLAG_KEY"
2let flagObserverOwner = flagKey as LDObserverOwner
4LDClient.shared.observe(keys: [flagKey], owner: flagObserverOwner, handler: { (changedFlags) in
5 if changedFlags[flagKey] != nil {
6 //Your code here
7 }
10LDClient.shared.stopObserving(owner: flagObserverOwner)
12LDClient.shared.observeFlagsUnchanged(owner: self) {
13 LDClient.shared.stopObserving(owner: self as LDObserverOwner)
16LDClient.shared.observeAll(owner: self) {_ in
17 LDClient.shared.stopObserving(owner: self as LDObserverOwner)

Background fetch

When the app is backgrounded, the V4 SDK does not receive real-time events. However, there is support for a background fetch to update flag values opportunistically, according to iOS standard defaults.

To change the background fetch interval for flags in your app, just add the following code in your LDConfig:

1var ldConfig = LDConfig(mobileKey: "MY_MOBILE_KEY")
3ldConfig.backgroundFlagPollingInterval = 3600

Monitoring SDK Status

This has been available since v4.2.0

The iOS SDK exposes some of its internal status through the Connection Status API to allow your application to monitor the SDK's status. This is provided primarily as a mechanism for the application to determine how recently the internal flag cache has been updated with the most recent values, as well as diagnosing potential reasons for the flag cache to be out of date.

The SDK has four connectivity states dependent on its configuration, application foreground state, network connectivity, as well as calls explicitly setting the client offline or online. A summary of these states is given below.

Connection ModeDescription
streamingThe SDK has an active streaming connection.
pollingThe SDK has an active polling connection.
offlineThe SDK is set offline or has no network connection.
establishingStreamingConnectionThe SDK is attempting to connect to LaunchDarkly by streaming.

The SDK also internally stores a timestamp of the most recent successful and failed connections to LaunchDarkly, as well as information related to the most recent failed connection. lastKnownFlagValidity is nil if either no connection has ever been successfully made or if the SDK has an active streaming connection. It will have a value if it is in polling mode and at least one poll has completed successfully, or 2) if in streaming mode whenever the streaming connection closes. The LDClient.shared method getConnectionInformation() returns a structure allowing retrieval of these fields.

The ConnectionInformation class can return four different values for lastFailureReason. A summary of these values is given below.

lastFailureReason valueDescription
noneThis will be returned when no error has been recorded.
unknownErrorThis will be returned when there is an internal error in the stream request.
unauthorizedThis will be returned when an incorrect mobile key is provided.
httpErrorThis will be returned when an error with an HTTP error code is present.

You can listen to changes in ConnectionInformation.ConnectionMode in a similar manner to flag observers. Here is an example of the new API.

1let connectionInformation = LDClient.shared.getConnectionInformation()
2print("Current Connection Status: \(connectionInformation.description())")
3//Setting a Connection Mode Listener
4LDClient.shared.observeCurrentConnectionMode(owner: self) { [weak self] (connectionMode) in
5 //do something after ConnectionMode was updated.
6 print("Connection Mode: \(connectionMode)")