LDClient

public class LDClient

The LDClient is the heart of the SDK, providing client apps running iOS, watchOS, macOS, or tvOS access to LaunchDarkly services. This singleton provides the ability to set a configuration (LDConfig) that controls how the LDClient talks to LaunchDarkly servers, and a user (LDUser) that provides finer control on the feature flag values delivered to LDClient. Once the LDClient has started, it connects to LaunchDarkly’s servers to get the feature flag values you set in the Dashboard.

Usage

Startup

  1. To customize, configure a LDConfig and LDUser. The config is required, the user is optional. Both give you additional control over the feature flags delivered to the LDClient. See LDConfig & LDUser for more details.
    • The mobileKey set into the LDConfig comes from your LaunchDarkly Account settings. If you have multiple projects be sure to choose the correct Mobile key.
  2. Call LDClient.start(config: user: completion:)
    • If you do not pass in a LDUser, LDClient will create a default for you.
    • The optional completion closure allows the LDClient to notify your app when it received flag values.
  3. Because LDClient instances are stored statically, you do not have to keep a reference to it in your code. Get the primary instances with LDClient.get()

Getting Feature Flags

Once the LDClient has started, it makes your feature flags available using the variation and variationDetail methods. 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.

 let boolFlag = LDClient.get()?.boolVariation(forKey: "my-bool-flag", defaultValue: false)

If you need to know more information about why a given value is returned, use variationDetail.

See boolVariation(forKey: defaultValue:) or boolVariationDetail(forKey: defaultValue:) for details

Observing Feature Flags

You might need to know when a feature flag value changes. This is not required, you can check the flag’s value when you need it.

If you want to know when a feature flag value changes, you can check the flag’s value. You can also use one of several observe methods to have the LDClient notify you when a change occurs. There are several options–you can set up notificiations based on when a specific flag changes, when any flag in a collection changes, or when a flag doesn’t change.

 LDClient.get()?.observe("flag-key", owner: self, observer: { [weak self] (changedFlag) in
    self?.updateFlag(key: "flag-key", changedFlag: changedFlag)
 }

The changedFlag passed in to the closure contains the old and new value of the flag.

State Controls and Indicators

  • Reports the online/offline state of the LDClient.

    When online, the SDK communicates with LaunchDarkly servers for feature flag values and event reporting.

    When offline, the SDK does not attempt to communicate with LaunchDarkly servers. Client apps can request feature flag values and set/change feature flag observers while offline. The SDK will collect events while offline.

    Use setOnline(_: completion:) to change the online/offline state.

    Declaration

    Swift

    public private(set) var isOnline: Bool { get set }
  • Reports the initialization state of the LDClient.

    When true, the SDK has either communicated with LaunchDarkly servers for feature flag values or the SDK has been set offline.

    When false, the SDK has not been able to communicate with LaunchDarkly servers. Client apps can request feature flag values and set/change feature flag observers but flags might not exist or be stale.

    Declaration

    Swift

    public var isInitialized: Bool { get }
  • Set the LDClient online/offline.

    When online, the SDK communicates with LaunchDarkly servers for feature flag values and event reporting.

    When offline, the SDK does not attempt to communicate with LaunchDarkly servers. Client apps can request feature flag values and set/change feature flag observers while offline. The SDK will collect events while offline.

    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 susequent 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.

    Declaration

    Swift

    public func setOnline(_ goOnline: Bool, completion: (() -> Void)? = nil)

    Parameters

    goOnline

    Desired online/offline mode for the LDClient

    completion

    Completion closure called when setOnline completes (Optional)

  • Returns an object containing information about successful and/or failed polling or streaming connections to LaunchDarkly

    Declaration

    Swift

    public func getConnectionInformation() -> ConnectionInformation
  • Stops the LDClient. Stopping the client means the LDClient goes offline and stops recording events. LDClient will no longer provide feature flag values, only returning default values.

    There is almost no reason to stop the LDClient. Normally, set the LDClient offline to stop communication with the LaunchDarkly servers. Stop the LDClient to stop recording events. There is no need to stop the LDClient prior to suspending, moving to the background, or terminating the app. The SDK will respond to these events as the system requires and as configured in LDConfig.

    Declaration

    Swift

    public func close()
  • The LDUser set into the LDClient may affect the set of feature flags returned by the LaunchDarkly server, and ties event tracking to the user. See LDUser for details about what information can be retained.

    Normally, the client app should create and set the LDUser and pass that into start(config: user: completion:).

    The client app can change the active user by calling identify with a new or updated LDUser. Client apps should follow Apple’s Privacy Policy when collecting user information.

    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 (see setOnline(_: completion:) for details). A completion may be passed to the identify method to allow a client app to know when fresh flag values for the new user are ready.

    Declaration

    Swift

    public func identify(user: LDUser, completion: (() -> Void)? = nil)

    Parameters

    user

    The LDUser set with the desired user.

    completion

    Closure called when the embedded setOnlineIdentify call completes, subject to throttling delays. (Optional)

  • Returns a dictionary with the flag keys and their values. If the LDClient is not started, returns nil.

    Declaration

    Swift

    public var allFlags: [LDFlagKey : LDValue]? { get }

Observing Updates

  • Sets a handler for the specified flag key executed on the specified owner. If the flag’s value changes, executes the handler, passing in the changedFlag containing the old and new flag values. See LDChangedFlag for details.

    The SDK retains only weak references to the owner, which allows the client app to freely destroy observer 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.

    SeeAlso: LDChangedFlag and stopObserving(owner:)

    Usage

    LDClient.get()?.observe("flag-key", owner: self) { [weak self] (changedFlag) in
       if let .bool(newValue) = changedFlag.newValue {
           // do something with the newValue
       }
    

    Declaration

    Swift

    public func observe(key: LDFlagKey, owner: LDObserverOwner, handler: @escaping LDFlagChangeHandler)

    Parameters

    key

    The LDFlagKey for the flag to observe.

    owner

    The LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.

    handler

    The closure the SDK will execute when the feature flag changes.

  • Sets a handler for the specified flag keys executed on the specified owner. If any observed flag’s value changes, executes the handler 1 time, passing in a dictionary of [LDFlagKey: LDChangedFlag] containing the old and new flag values. See LDChangedFlag for details.

    The SDK retains only weak references to owner, which allows the client app to freely destroy observer 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.

    SeeAlso: LDChangedFlag and stopObserving(owner:)

    Usage

    LDClient.get()?.observe(flagKeys, owner: self) { [weak self] (changedFlags) in     // changedFlags is a [LDFlagKey: LDChangedFlag]
       //There will be an LDChangedFlag entry in changedFlags for each changed flag. The closure will only be called once regardless of how many flags changed.
       if let someChangedFlag = changedFlags["some-flag-key"] {    // someChangedFlag is a LDChangedFlag
           //do something with someChangedFlag
        }
    }
    

    Declaration

    Swift

    public func observe(keys: [LDFlagKey], owner: LDObserverOwner, handler: @escaping LDFlagCollectionChangeHandler)

    Parameters

    keys

    An array of LDFlagKeys for the flags to observe.

    owner

    The LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.

    handler

    The LDFlagCollectionChangeHandler the SDK will execute 1 time when any of the observed feature flags change.

  • Sets a handler for all flag keys executed on the specified owner. If any flag’s value changes, executes the handler 1 time, passing in a dictionary of [LDFlagKey: LDChangedFlag] containing the old and new flag values. See LDChangedFlag for details.

    The SDK retains only weak references to owner, which allows the client app to freely destroy observer 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.

    SeeAlso: LDChangedFlag and stopObserving(owner:)

    Usage

    LDClient.get()?.observeAll(owner: self) { [weak self] (changedFlags) in     // changedFlags is a [LDFlagKey: LDChangedFlag]
       //There will be an LDChangedFlag entry in changedFlags for each changed flag. The closure will only be called once regardless of how many flags changed.
       if let someChangedFlag = changedFlags["some-flag-key"] {    // someChangedFlag is a LDChangedFlag
           //do something with someChangedFlag
       }
    }
    

    Declaration

    Swift

    public func observeAll(owner: LDObserverOwner, handler: @escaping LDFlagCollectionChangeHandler)

    Parameters

    owner

    The LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.

    handler

    The LDFlagCollectionChangeHandler the SDK will execute 1 time when any of the observed feature flags change.

  • Sets a handler executed when a flag update leaves the flags unchanged from their previous values.

    This handler can only ever be called when the LDClient is polling.

    The SDK retains only weak references to owner, which allows the client app to freely destroy observer 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.

    SeeAlso: stopObserving(owner:)

    Usage

    LDClient.get()?.observeFlagsUnchanged(owner: self) { [weak self] in
        // Do something after an update was received that did not update any flag values.
        //The closure will be called once on the main thread after the update.
    }
    

    Declaration

    Swift

    public func observeFlagsUnchanged(owner: LDObserverOwner, handler: @escaping LDFlagsUnchangedHandler)

    Parameters

    owner

    The LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.

    handler

    The LDFlagsUnchangedHandler the SDK will execute 1 time when a flag request completes with no flags changed.

  • Sets a handler executed when ConnectionInformation.currentConnectionMode changes.

    The SDK retains only weak references to owner, which allows the client app to freely destroy change 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.

    SeeAlso: stopObserving(owner:)

    Usage

    LDClient.get()?.observeCurrentConnectionMode(owner: self) { [weak self] in
       //do something after ConnectionMode was updated.
    }
    

    Declaration

    Swift

    public func observeCurrentConnectionMode(owner: LDObserverOwner, handler: @escaping LDConnectionModeChangedHandler)

    Parameters

    owner

    The LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.

    handler

    The LDConnectionModeChangedHandler the SDK will execute 1 time when ConnectionInformation.currentConnectionMode is changed.

  • Removes all observers for the given owner, including the flagsUnchangedObserver

    The client app does not have to call this method. If the client app deinits a LDFlagChangeOwner, the SDK will automatically remove its handlers without ever calling them again.

    Declaration

    Swift

    public func stopObserving(owner: LDObserverOwner)

    Parameters

    owner

    The LDFlagChangeOwner owning the handlers to remove, whether a flag change handler or flags unchanged handler.

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. Ths 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. See LDConfig for details.

    Usage

    let appEventData: LDValue = ["some-custom-key: "some-custom-value", "another-custom-key": 7]
    LDClient.get()?.track(key: "app-event-key", data: appEventData)
    

    Declaration

    Swift

    public func track(key: String, data: LDValue? = nil, metricValue: Double? = nil)

    Parameters

    key

    The key for the event.

    data

    The data for the event. (Optional)

    metricValue

    A numeric value used by the LaunchDarkly experimentation feature in numeric custom metrics. Can be omitted if this event is used by only non-numeric metrics. This field will also be returned as part of the custom event for Data Export. (Optional)

  • Tells the SDK to generate an alias event.

    Associates two users for analytics purposes.

    This can be helpful in the situation where a person is represented by multiple LaunchDarkly users. This may happen, for example, when a person initially logs into an application– the person might be represented by an anonymous user prior to logging in and a different user after logging in, as denoted by a different user key.

    Declaration

    Swift

    public func alias(context new: LDUser, previousContext old: LDUser)

    Parameters

    context

    the user that will be aliased to

    previousContext

    the user that will be bound to the new context

  • Tells the SDK to immediately send any currently queued events to LaunchDarkly.

    There should not normally be a need to call this function. While online, the LDClient automatically reports events on an interval defined by LDConfig.eventFlushInterval. Note that this function does not block until events are sent, it only triggers a background task to send events immediately.

    Declaration

    Swift

    public func flush()

Initializing and Accessing

  • Starts the LDClient using the passed in config & user. Call this before requesting feature flag values. The LDClient will not go online until you call this method. Starting the LDClient means setting the config & user, setting the client online if config.startOnline is true (the default setting), and starting event recording. The client app must start the LDClient before it will report feature flag values. If a client does not call start, no methods will work. If the start call omits the user, the LDClient uses a default LDUser. If thestart call includes the optional completion closure, LDClient calls the completion closure when setOnline(_: completion:) embedded in the init method completes. This method listens for flag updates so the completion will only return once an update has occurred. The start call is subject to throttling delays, therefore the completion closure call may be delayed. Subsequent calls to this method cause the LDClient to return. Normally there should only be one call to start. To change user, use identify.

    Declaration

    Swift

    public static func start(config: LDConfig, user: LDUser? = nil, completion: (() -> Void)? = nil)

    Parameters

    configuration

    The LDConfig that contains the desired configuration. (Required)

    user

    The LDUser set with the desired user. If omitted, LDClient sets a default user. (Optional)

    completion

    Closure called when the embedded setOnline call completes. (Optional)

  • See start for more information on starting the SDK.

    Declaration

    Swift

    public static func start(config: LDConfig, user: LDUser? = nil, startWaitSeconds: TimeInterval, completion: ((_ timedOut: Bool) -> Void)? = nil)

    Parameters

    configuration

    The LDConfig that contains the desired configuration. (Required)

    user

    The LDUser set with the desired user. If omitted, LDClient sets a default user. (Optional)

    startWaitSeconds

    A TimeInterval that determines when the completion will return if no flags have been returned from the network.

    completion

    Closure called when the embedded setOnline call completes. Takes a Bool that indicates whether the completion timedout as a parameter. (Optional)

  • Returns the LDClient instance for a given environment.

    Declaration

    Swift

    public static func get(environment: String = LDConfig.Constants.primaryEnvironmentName) -> LDClient?

    Parameters

    environment

    The name of an environment provided in LDConfig.secondaryMobileKeys, defaults to LDConfig.Constants.primaryEnvironmentName which is always associated with the LDConfig.mobileKey environment.

    Return Value

    The requested LDClient instance.

Flag variation methods

  • Returns the boolean value of a feature flag for a given flag key.

    Declaration

    Swift

    public func boolVariation(forKey flagKey: LDFlagKey, defaultValue: Bool) -> Bool

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    the variation for the selected user, or defaultValue if the flag is not available.

  • Returns the boolean value of a feature flag for a given flag key, in an object that also describes the way the value was determined.

    Declaration

    Swift

    public func boolVariationDetail(forKey flagKey: LDFlagKey, defaultValue: Bool) -> LDEvaluationDetail<Bool>

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    an LDEvaluationDetail object

  • Returns the integer value of a feature flag for a given flag key.

    Declaration

    Swift

    public func intVariation(forKey flagKey: LDFlagKey, defaultValue: Int) -> Int

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    the variation for the selected user, or defaultValue if the flag is not available.

  • Returns the integer value of a feature flag for a given flag key, in an object that also describes the way the value was determined.

    Declaration

    Swift

    public func intVariationDetail(forKey flagKey: LDFlagKey, defaultValue: Int) -> LDEvaluationDetail<Int>

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    an LDEvaluationDetail object

  • Returns the double-precision floating-point value of a feature flag for a given flag key.

    Declaration

    Swift

    public func doubleVariation(forKey flagKey: LDFlagKey, defaultValue: Double) -> Double

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    the variation for the selected user, or defaultValue if the flag is not available.

  • Returns the double-precision floating-point value of a feature flag for a given flag key, in an object that also describes the way the value was determined.

    Declaration

    Swift

    public func doubleVariationDetail(forKey flagKey: LDFlagKey, defaultValue: Double) -> LDEvaluationDetail<Double>

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    an LDEvaluationDetail object

  • Returns the string value of a feature flag for a given flag key.

    Declaration

    Swift

    public func stringVariation(forKey flagKey: LDFlagKey, defaultValue: String) -> String

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    the variation for the selected user, or defaultValue if the flag is not available.

  • Returns the string value of a feature flag for a given flag key, in an object that also describes the way the value was determined.

    Declaration

    Swift

    public func stringVariationDetail(forKey flagKey: LDFlagKey, defaultValue: String) -> LDEvaluationDetail<String>

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    an LDEvaluationDetail object

  • Returns the JSON value of a feature flag for a given flag key.

    Declaration

    Swift

    public func jsonVariation(forKey flagKey: LDFlagKey, defaultValue: LDValue) -> LDValue

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    the variation for the selected user, or defaultValue if the flag is not available.

  • Returns the JSON value of a feature flag for a given flag key, in an object that also describes the way the value was determined.

    Declaration

    Swift

    public func jsonVariationDetail(forKey flagKey: LDFlagKey, defaultValue: LDValue) -> LDEvaluationDetail<LDValue>

    Parameters

    forKey

    the unique feature key for the feature flag.

    defaultValue

    the default value for if the flag value is unavailable.

    Return Value

    an LDEvaluationDetail object