• HOME
  • INTEGRATIONS
  • SDKS
  • GUIDES
  • API DOCS
No results for ""
EXPAND ALL
launchdarkly.com

EDIT ON GITHUB

iOS SDK reference

Read time: 10 minutes
Last edited: Dec 01, 2020
Swift and Objective-C compatibility

This documentation is for the latest version of the LaunchDarkly SDK for iOS.

SDK versions 4.0.0 and later are written in Swift. These versions are compatible with applications written in either Swift or Objective-C. See inline code samples throughout the documentation for use with either language.

Earlier versions of this SDK were written in 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, view the source on the iOS SDK GitHub repository or the generated API docs. 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, the following steps will get you started with using the LaunchDarkly SDK in your application.

Including the SDK as a dependency

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.

Swift Package Manager



If you're using the Swift Package Manager, you can install the SDK through Xcode or include it as a dependency in your Package.swift file.

To add a package dependency to your Xcode project, select File > Swift Packages > Add Package Dependency and enter the iOS SDK repository URL clone URL, then select your desired version constraints.

Including the SDK as a dependency in a Package.swift file would look like this:

1//...
2 dependencies: [
3 .package(url: "https://github.com/launchdarkly/ios-client-sdk.git", .upToNextMinor("5.1.0")),
4 ],
5 targets: [
6 .target(
7 name: "YOUR_TARGET",
8 dependencies: ["LaunchDarkly"]
9 )
10 ],
11//...

CocoaPods



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.

1use_frameworks!
2target 'YourTargetName' do
3 pod 'LaunchDarkly', ~> '5.1'
4end

Carthage



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" ~> 5.1

Manually



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

Using the SDK in your application

This is a brief overview of using the SDK, see the detailed sections below for more information on configuration and advanced features.

Importing



First import the LaunchDarkly client in your application code.

1import LaunchDarkly

Initializing



Now that the SDK is imported, it can be configured and initialized. You should specify your mobile key when configuring the SDK so that your application will be authorized to connect to LaunchDarkly, retrieve flags for your environment, and report events.

Mobile Keys

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

1let config = LDConfig(mobileKey: "YOUR_MOBILE_KEY")
2let user = LDUser(key: "test-user")
3
4LDClient.start(config: config, user: user)
5
6// If you need to ensure that the most recent flags have been received
7// start supports an optional completion that is triggered when the SDK
8// has retrieved flags for the configured user.
9LDClient.start(config: config, user: user) {
10 // Client has received flags for the user
11}
12
13// If you would like the completion to be called even in cases where
14// the SDK is unable to retrieve flags for the user, there is a variant
15// to the start method that takes a maximum time to wait for flag values.
16// This variant notifies the completion whether the operation timed out.
17LDClient.start(config: config, user: user, startWaitSeconds: 5) { timedOut in
18 if timedOut {
19 // The SDK may not have the most recent flags for the configured user
20 } else {
21 // The SDK has received flags for the configured user
22 }
23}

Retrieving the client instance



After calling start, the LDClient instance can be retrieve with the static method LDClient.get().

1let ldClient = LDClient.get()!

Getting the variation to serve the configured user



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

1let showFeature = ldClient.variation(forKey: "flag-key", defaultValue: false)
2
3if showFeature {
4 // application code to show the feature
5else {
6 // the code to run if the feature is off
7}

Terminating the client instance



Lastly, when your application is about to terminate, shut down the LDClient instance. 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 one time.

1ldClient.close()

Client Configuration Options

You can also pass other custom parameters to the client with the configuration object:

1var ldConfig = LDConfig(mobileKey: "YOUR_MOBILE_KEY")
2ldConfig.connectionTimeout = 10.0
3ldConfig.eventFlushInterval = 30.0

Here, we've customized the client connection timeout and event flush interval parameters. To learn more about the specific configuration options that are available in this SDK, read the SDK's API docs.

User Configuration Options

You can also pass optional properties to the user object:

1var user = LDUser(key: "YOUR_USER_KEY")
2user.name = "Human Person"
3user.email = "human@example.com"

Here, we've added the user's full name and email address. To learn more about the specific user properties that are available in this SDK, read the SDK's API docs.

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 is removed before the user is sent to LaunchDarkly.

You can also mark attributes as private on a particular LDUser instance, for example:

1var user = LDUser(key: "USER_KEY", name: "USER_NAME")
2user.privateAttributes = ["name"]

Anonymous Users

You can also declare a LDUser to be an anonymous, not logged-in user:

1var user = LDUser(key: "USER_KEY")
2user.isAnonymous = true
3
4// OR have the SDK use a device persistent key, this sets `isAnonymous` by default.
5let user = LDUser()

You must 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!

Variation

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 boolFlagValue = LDClient.get()!.variation(forKey: "bool-flag-key", defaultValue: false)
2let dictionaryFlagValue = LDClient.get()!.variation(forKey: "dictionary-flag-key", defaultValue: ["a": 1, "b": 2] as [String: 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 default value. Use this method when the default value is a non-Optional type. See variation with the Optional return value when the default 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 always returns the default 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 learns 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 returns 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 receive feature flag default 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.

VariationDetail

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.

Returns a dictionary with the flag keys and their values. If the LDClient is not started, returns nil. The dictionary does not contain feature flags from the server with null values. LDClient does 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.get()!.allFlags

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 track, 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.

Once the SDK's event store is full, the SDK discards new events until the event store is cleared when reporting events to LaunchDarkly. Configure the size of the event store using LDConfig.eventCapacity. 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 an LDInvalidArgumentError 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.

1try {
2 let data = ["some-custom-key": "some-custom-value", "another-custom-key": 7] as [String: Any]
3 try LDClient.get()!.track(key: "MY_TRACK_EVENT_NAME", data: data)
4} catch is LDInvalidArgumentError {
5 // Do something with the error
6} catch {}

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) proceeds, 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 calls the closure immediately on completion of this method. For throttled setOnline(true) calls, the SDK calls the closure after the throttling delay at the completion of the setOnline method.

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

Use isOnline to get the online/offline state.

1LDClient.get()!.setOnline(false)
2LDClient.get()!.setOnline(true) {
3 // Client is online
4}
5let connectionStatus = LDClient.get()!.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 uses the latest stored flag settings in memory. If there are no previously stored flag settings, then the default values are used.

Reporting Events

Internally, the LaunchDarkly SDK keeps an event buffer for track 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 flush to process events immediately.

1LDClient.get()!.flush()

Changing the user context

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 stores 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:

1let newUser = LDUser(key: "NEW_USER_KEY")
2LDClient.get()!.identify(user: newUser)
3
4// identify can also be called with a completion
5LDClient.get()!.identify(user: newUser) {
6 // Flags have been retrieved for the new user
7}

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 updates 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
3
4let ldClient = LDClient.get()!
5
6ldClient.observe(keys: [flagKey], owner: flagObserverOwner, handler: { changedFlags in
7 if changedFlags[flagKey] != nil {
8 // Your code here
9 }
10})
11
12ldClient.stopObserving(owner: flagObserverOwner)
13
14ldClient.observeFlagsUnchanged(owner: self) {
15 ldClient.stopObserving(owner: self as LDObserverOwner)
16}
17
18ldClient.observeAll(owner: self) {_ in
19 ldClient.stopObserving(owner: self as LDObserverOwner)
20}

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")
2ldConfig.backgroundFlagPollingInterval = 3600

Monitoring SDK Status

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 has 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 returns when no error has been recorded.
unknownErrorThis returns when there is an internal error in the stream request.
unauthorizedThis returns when an incorrect mobile key is provided.
httpErrorThis returns 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.

1// Get current connection information
2let connectionInformation = LDClient.get()!.getConnectionInformation()
3// Setting a connection mode update observer
4LDClient.get()!.observeCurrentConnectionMode(owner: self) { [weak self] connectionMode in
5 // do something after ConnectionMode was updated.
6}

Multiple environments

LaunchDarkly's iOS SDK supports having multiple LDClient instances tied to separate mobile keys. This allows evaluating flags from multiple environments.

All LDClient instances evaluate against the same LDUser. The mobile keys for additional environments are specified, along with identifying names, in a map passed to your LDConfig object.

1let user = LDUser(key: "YOUR_USER_KEY")
2var config = LDConfig(mobileKey: "PRIMARY_MOBILE_KEY")
3// Note that the SDK will throw error strings if you add duplicate keys or put the primary key or name in secondaryMobileKeys.
4try! config.setSecondaryMobileKeys(["platform": "PLATFORM_MOBILE_KEY", "core": "CORE_MOBILE_KEY"])
5LDClient.start(config: config, user: user)

To access the secondary mobile key instances, use the LDClient.get static method, passing the indentifier assigned to your environment key in the secondaryMobileKeys map.

1var coreInstance = LDClient.get(environment: "core")
2let coreFlagValue = coreInstance?.variation(forKey: "CORE_FLAG_KEY", defaultValue: false)

As all the client instances use the same LDUser object, some SDK functionality affects all instances.

1coreInstance.identify(/*User Object*/)
2coreInstance.flush()
3coreInstance.setOnline(true)
4coreInstance.close()

Track calls, listeners, and flag evaluation are all tied to the client instance they are evaluated against.

Data collection

To learn more about data collection within this SDK and implications on submissions to the Apple App Store, read Apple App Store data collection policy.