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 contexts (LDContext) 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
- To customize, configure a
LDConfigandLDContext. Theconfigis required, thecontextis optional. Both give you additional control over the feature flags delivered to the LDClient. SeeLDConfig&LDContextfor more details.- The mobileKey set into the
LDConfigcomes from your LaunchDarkly Account settings. If you have multiple projects be sure to choose the correct Mobile key.
- The mobileKey set into the
- Call
LDClient.start(config: context: completion:)- If you do not pass in a LDContext, LDClient will create a default for you.
- The optional completion closure allows the LDClient to notify your app when it received flag values.
- 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. The flag change listener may be invoked multiple times per invocation of LDClient.identify as the SDK fetches up to date flag data from multiple sources (e.g. local cache, cloud services). In certain error cases, the SDK may not be able to retrieve flag data during an identify (e.g. no network connectivity). In those cases, the flag change listener may not be invoked.
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.
-
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 calledsetOnline(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 tostart(config: context: completion:), and setting theconfigorcontextcan also callsetOnline(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 allsetOnline(false)calls, the SDK will call the closure immediately on completion of this method. For throttledsetOnline(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
mobileKeyis empty. For macOS, the SDK will not go online in the background unlessenableBackgroundUpdatesis true.Use
isOnlineto get the online/offline state.Declaration
Swift
public func setOnline(_ goOnline: Bool, completion: (() -> Void)? = nil)Parameters
goOnlineDesired online/offline mode for the LDClient
completionCompletion 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 LDContext set into the LDClient may affect the set of feature flags returned by the LaunchDarkly server, and ties event tracking to the context. See
LDContextfor details about what information can be retained.Normally, the client app should create and set the LDContext and pass that into
start(config: context: completion:).The client app can change the active
contextby calling identify with a new or updated LDContext. Client apps should follow Apple’s Privacy Policy when collecting user information.When a new context is set, the LDClient goes offline and sets the new context. If the client was online when the new context 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 context are ready.Declaration
Swift
@available(*, deprecated, message: "Use LDClient.identify(context: completion:﹚ with non-optional completion parameter") public func identify(context: LDContext, completion: (() -> Void)? = nil)Parameters
contextThe LDContext set with the desired context.
completionClosure called when the embedded
setOnlineIdentifycall completes, subject to throttling delays. (Optional) -
The LDContext set into the LDClient may affect the set of feature flags returned by the LaunchDarkly server, and ties event tracking to the context. See
LDContextfor details about what information can be retained.Normally, the client app should create and set the LDContext and pass that into
start(config: context: completion:).The client app can change the active
contextby calling identify with a new or updated LDContext. Client apps should follow Apple’s Privacy Policy when collecting user information.When a new context is set, the LDClient goes offline and sets the new context. If the client was online when the new context 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 context are ready.While only a single identify request can be active at a time, consumers of this SDK can call this method multiple times. To prevent unnecessary network traffic, these requests are placed into a sheddable queue. Identify requests will be shed if 1) an existing identify request is in flight, and 2) a third identify has been requested which can be replace the one being shed.
Declaration
Swift
public func identify(context: LDContext, completion: @escaping (_ result: IdentifyResult) -> Void)Parameters
contextThe LDContext set with the desired context.
completionClosure called when the embedded
setOnlineIdentifycall completes, subject to throttling delays. -
Sets the LDContext into the LDClient inline with the behavior detailed on
LDClient.identify(context: completion:). Additionally, this method allows specifying how the flag cache should be handled when transitioning between contexts through theuseCacheparameter.To learn more about these cache transitions, refer to the
IdentifyCacheUsagedocumentation.Declaration
Swift
public func identify(context: LDContext, useCache: IdentifyCacheUsage, completion: @escaping (_ result: IdentifyResult) -> Void)Parameters
contextThe LDContext set with the desired context.
useCacheHow to handle flag caches during identify transition.
completionClosure called when the embedded
setOnlineIdentifycall completes, subject to throttling delays. -
Sets the LDContext into the LDClient inline with the behavior detailed on
LDClient.identify(context: completion:). Additionally, this method will ensure thecompletionparameter will be called within the specified time interval.Note that the
completionmethod being invoked does not mean that the identify request has been cancelled. The identify request will continue attempting to complete as it would withLDClient.identify(context: completion:). Subsequent identify requests queued behind a timed out request will remain blocked (or shed) until the in flight request completes.Declaration
Swift
public func identify(context: LDContext, timeout: TimeInterval, completion: @escaping ((_ result: IdentifyResult) -> Void))Parameters
contextThe LDContext set with the desired context.
timeoutThe upper time limit before the
completioncallback will be invoked.completionClosure called when the embedded
setOnlineIdentifycall completes, subject to throttling delays. -
Sets the LDContext into the LDClient inline with the behavior detailed on
LDClient.identify(context: timeout: completion:). Additionally, this method allows specifying how the flag cache should be handled when transitioning between contexts through theuseCacheparameter.To learn more about these cache transitions, refer to the
IdentifyCacheUsagedocumentation.Declaration
Swift
public func identify(context: LDContext, timeout: TimeInterval, useCache: IdentifyCacheUsage, completion: @escaping ((_ result: IdentifyResult) -> Void))Parameters
contextThe LDContext set with the desired context.
timeoutThe upper time limit before the
completioncallback will be invoked.useCacheHow to handle flag caches during identify transition.
completionClosure called when the embedded
setOnlineIdentifycall completes, subject to throttling delays.
-
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
changedFlagcontaining the old and new flag values. SeeLDChangedFlagfor 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:
LDChangedFlagandstopObserving(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
keyThe LDFlagKey for the flag to observe.
ownerThe LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.
handlerThe 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
LDChangedFlagfor 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:
LDChangedFlagandstopObserving(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
keysAn array of LDFlagKeys for the flags to observe.
ownerThe LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.
handlerThe 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
LDChangedFlagfor 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:
LDChangedFlagandstopObserving(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
ownerThe LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.
handlerThe 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
ownerThe LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.
handlerThe 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
ownerThe LDObserverOwner which will execute the handler. The SDK retains a weak reference to the owner.
handlerThe 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
ownerThe LDFlagChangeOwner owning the handlers to remove, whether a flag change handler or flags unchanged handler.
-
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
eventCapacityon theconfig. SeeLDConfigfor 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
keyThe key for the event.
dataThe data for the event. (Optional)
metricValueA 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 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()
-
Starts the LDClient using the passed in
config&context. Call this before requesting feature flag values. The LDClient will not go online until you call this method. Starting the LDClient means setting theconfig&context, setting the client online ifconfig.startOnlineis 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 callstart, no methods will work. If thestartcall omits thecontext, the LDClient uses a defaultLDContext. If thestartcall includes the optionalcompletionclosure, LDClient calls thecompletionclosure whensetOnline(_: completion:)embedded in theinitmethod completes. This method listens for flag updates so the completion will only return once an update has occurred. Thestartcall is subject to throttling delays, therefore thecompletionclosure call may be delayed. Subsequent calls to this method cause the LDClient to return. Normally there should only be one call to start. To changecontext, useidentify.Declaration
Parameters
configurationThe LDConfig that contains the desired configuration. (Required)
contextThe LDContext set with the desired context. If omitted, LDClient sets a default context. (Optional)
completionClosure called when the embedded
setOnlinecall completes. (Optional) -
See start for more information on starting the SDK.
Declaration
Parameters
configurationThe LDConfig that contains the desired configuration. (Required)
contextThe LDContext set with the desired context. If omitted, LDClient sets a default context. (Optional)
startWaitSecondsA TimeInterval that determines when the completion will return if no flags have been returned from the network. If you use a large TimeInterval and wait for the timeout, then any network delays will cause your application to wait a long time before continuing execution.
completionClosure called when the embedded
setOnlinecall 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
environmentThe name of an environment provided in LDConfig.secondaryMobileKeys, defaults to
LDConfig.Constants.primaryEnvironmentNamewhich is always associated with theLDConfig.mobileKeyenvironment.Return Value
The requested LDClient instance.
-
Returns the boolean value of a feature flag for a given flag key.
Declaration
Swift
public func boolVariation(forKey flagKey: LDFlagKey, defaultValue: Bool) -> BoolParameters
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
the variation for the selected context, or
defaultValueif 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
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
an
LDEvaluationDetailobject -
Returns the integer value of a feature flag for a given flag key.
Declaration
Swift
public func intVariation(forKey flagKey: LDFlagKey, defaultValue: Int) -> IntParameters
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
the variation for the selected context, or
defaultValueif 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
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
an
LDEvaluationDetailobject -
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) -> DoubleParameters
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
the variation for the selected context, or
defaultValueif 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
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
an
LDEvaluationDetailobject -
Returns the string value of a feature flag for a given flag key.
Declaration
Swift
public func stringVariation(forKey flagKey: LDFlagKey, defaultValue: String) -> StringParameters
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
the variation for the selected context, or
defaultValueif 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
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
an
LDEvaluationDetailobject -
Returns the JSON value of a feature flag for a given flag key.
Declaration
Parameters
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
the variation for the selected context, or
defaultValueif 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
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
an
LDEvaluationDetailobject -
Returns the value of a feature flag for a given flag key, converting the raw JSON value into a type of your specification.
Declaration
Swift
public func variation<T>(forKey flagKey: LDFlagKey, defaultValue: T) -> T where T : LDValueConvertible, T : DecodableParameters
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
the variation for the selected context, or
defaultValueif the flag is not available. -
Returns the value of a feature flag for a given flag key, converting the raw JSON value into a type of your specifification, and including it in an object that also describes the way the value was determined.
Declaration
Swift
public func variationDetail<T>(forKey flagKey: LDFlagKey, defaultValue: T) -> LDEvaluationDetail<T> where T : LDValueConvertible, T : DecodableParameters
forKeythe unique feature key for the feature flag.
defaultValuethe default value for if the flag value is unavailable.
Return Value
an
LDEvaluationDetailobject
View on GitHub