### Minimal LaunchDarkly SDK Setup Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Initialize the LaunchDarkly SDK with a mobile key, create a user context, start the client, and retrieve a boolean flag. ```swift import LaunchDarkly // 1. Configure var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") // 2. Create context let context = try LDContextBuilder(key: "user-123").build() // 3. Start SDK LDClient.start(config: config, context: context) // 4. Use flags let showFeature = LDClient.get()?.boolVariation(forKey: "my-flag", defaultValue: false) ?? false ``` -------------------------------- ### Complete SDK Setup with Custom Hooks and Plugins Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/07-hooks-and-plugins.md Demonstrates how to define a custom hook, configure the SDK with this hook and environment metadata plugin, and start the client. Use this for integrating custom logic into the evaluation process or adding SDK metadata. ```swift import LaunchDarkly // Define custom hooks class MetricsHook: Hook { var evaluationCount = 0 func beforeEvaluation(seriesContext: EvaluationSeriesContext, seriesData: EvaluationSeriesData) -> EvaluationSeriesData { return seriesData } func afterEvaluation(seriesContext: EvaluationSeriesContext, seriesData: EvaluationSeriesData, evaluationDetail: LDEvaluationDetail) -> EvaluationSeriesData { evaluationCount += 1 return seriesData } } // Configure SDK var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") // Add hooks and plugins let metricsHook = MetricsHook() config.hooks = [metricsHook] config.plugins = [EnvironmentMetadata(...)] // Start let context = try LDContextBuilder(key: "user-123").build() LDClient.start(config: config, context: context) // Later: check metrics print("Total evaluations: \(metricsHook.evaluationCount)") ``` -------------------------------- ### GET Request Example Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/09-networking.md An example of an HTTP GET request to the LaunchDarkly service. ```http GET /meval HTTP/1.1 Host: app.launchdarkly.com Authorization: Bearer YOUR_MOBILE_KEY User-Agent: LaunchDarkly-iOS/11.2.0 ``` -------------------------------- ### Multi-Context Example Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/04-context-api.md Demonstrates the creation and usage of multi-contexts, which can contain multiple context objects for targeting. ```APIDOC ## Multi-Context Example ### Description Multi-contexts contain multiple context objects. You can target rules based on any context kind in the multi-context. ### Example: Organization + User Targeting ```swift let userContext = try LDContextBuilder(key: "user-123") .name("Alice") .kind(.user) .build() let orgContext = try LDContextBuilder(key: "org-456") .kind(.custom("organization")) .set("plan", value: .string("enterprise")) .build() var multiBuilder = LDMultiContextBuilder() try multiBuilder.add(userContext) try multiBuilder.add(orgContext) let multiContext = try multiBuilder.build() // In LaunchDarkly dashboard, you can now create rules like: // - "If user is Alice AND organization plan is enterprise" ``` ``` -------------------------------- ### Initialize SDK Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Start the LaunchDarkly client with configuration and an initial user context. The completion handler is called once initialization is complete. ```swift var config = LDConfig(mobileKey: "YOUR_KEY") let context = try LDContextBuilder(key: "user-123").build() LDClient.start(config: config, context: context) { print("SDK initialized, flags available") } // Or check manually if LDClient.get()?.isInitialized ?? false { print("SDK is initialized") } else { print("Waiting for flags...") } ``` -------------------------------- ### Creating Contexts with LDContextBuilder Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/04-context-api.md Examples of creating different types of contexts (user, device, custom) using the `LDContextBuilder`. ```APIDOC ## Example Usage of Context Kinds ### Creating Contexts with `LDContextBuilder` Use `LDContextBuilder` to construct contexts with specific kinds. ```swift let userContext = try LDContextBuilder(key: "user-123") .kind(.user) .build() let deviceContext = try LDContextBuilder(key: "device-456") .kind(.custom("device")) .build() let customContext = try LDContextBuilder(key: "custom-789") .kind(.custom("my-custom-kind")) .build() ``` ``` -------------------------------- ### LDClient.start(config:context:completion:) Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/01-ldclient-initialization.md Initializes and starts the LDClient singleton instance. This method is the primary entry point for using the LaunchDarkly SDK. ```APIDOC ## `LDClient.start(config:context:completion:)` ### Description Initializes and starts the LDClient singleton instance. ### Method Signature ```swift public static func start(config: LDConfig, context: LDContext? = nil, completion: (() -> Void)? = nil) -> LDClient? ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config | `LDConfig` | Yes | — | Configuration for the SDK, including the mobile key, base URLs, and feature flag polling intervals | | context | `LDContext` | No | auto-generated user context | The user or multi-context identifying the client. If not provided, the SDK creates a default user context with a randomly generated key | | completion | `() -> Void` | No | nil | Optional completion closure invoked when the SDK has fetched initial flag values or encountered an error | ### Returns An optional `LDClient` instance. Returns `nil` if called with an empty mobile key. ### Throws None (errors are handled through logging and completion callback behavior). ### Example ```swift import LaunchDarkly // Create a basic configuration var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") config.baseUrl = URL(string: "https://app.launchdarkly.com")! // Create a context representing the user let context = try LDContextBuilder(key: "user-123") .name("Alice Smith") .build() // Start the client LDClient.start(config: config, context: context) { print("SDK initialized with flag values") } // Access the client from anywhere in your app if let client = LDClient.get() { let showFeature = client.boolVariation(forKey: "new-feature", defaultValue: false) } ``` ``` -------------------------------- ### Minimal LaunchDarkly SDK Setup Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/README.md Initialize the LaunchDarkly SDK with a mobile key and a user context, then retrieve a boolean flag value. ```swift LDClient.start( config: LDConfig(mobileKey: "key"), context: try LDContextBuilder(key: "user-1").build() ) let value = LDClient.get()?.boolVariation(forKey: "flag", defaultValue: false) ?? false ``` -------------------------------- ### LaunchDarkly SDK Setup with Error Handling Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/README.md Initialize the LaunchDarkly SDK with a mobile key and a user context, including error handling for context building. ```swift do { let context = try LDContextBuilder(key: "user-123") .name("Alice") .build() var config = LDConfig(mobileKey: "YOUR_KEY") LDClient.start(config: config, context: context) { print("SDK initialized") } } catch { print("Error: \(error)") } ``` -------------------------------- ### Example Analytics Plugin Implementation Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/07-hooks-and-plugins.md An example of an analytics plugin that records flag evaluation events. Implement the `recordFlagEvaluation` method to send custom analytics data. ```swift class AnalyticsPlugin: Plugin { var metadata: PluginMetadata { return PluginMetadata( name: "analytics-plugin", version: "1.0.0", custom: ["type": .string("analytics")] ) } func configure(context: LDContext) -> Bool { print("Analytics plugin configured for context: \(context.key)") return true } func recordFlagEvaluation(flagKey: String, value: LDValue, context: LDContext) { // Send analytics event let event = [ "type": "flag_evaluation", "flag": flagKey, "user": context.key, "timestamp": ISO8601DateFormatter().string(from: Date()) ] // Send to analytics service } } // Configure var config = LDConfig(mobileKey: "YOUR_KEY") config.plugins = [AnalyticsPlugin()] ``` -------------------------------- ### REPORT Request Example Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/09-networking.md An example of an HTTP REPORT request to the LaunchDarkly service, including a JSON payload. ```http REPORT /meval HTTP/1.1 Host: app.launchdarkly.com Authorization: Bearer YOUR_MOBILE_KEY User-Agent: LaunchDarkly-iOS/11.2.0 Content-Type: application/json { "kind": "user", "key": "user-123" } ``` -------------------------------- ### Initialize and Use LaunchDarkly SDK in Swift Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/README.md Minimal code to configure the SDK with your mobile key, create a user context, start the client, and retrieve a boolean flag. Replace 'YOUR_MOBILE_KEY' and 'user-123' with your actual values. ```swift import LaunchDarkly // Configure var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") // Create context let context = try LDContextBuilder(key: "user-123").build() // Start SDK LDClient.start(config: config, context: context) // Use flags let showFeature = LDClient.get()?.boolVariation(forKey: "my-flag", defaultValue: false) ?? false ``` -------------------------------- ### Initialize LaunchDarkly SDK with Custom Configuration Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/05-ldconfig.md Configure the LaunchDarkly SDK with custom settings for streaming, events, polling, privacy, and performance. This example demonstrates setting a mobile key, enabling streaming, and defining private context attributes. ```swift import LaunchDarkly var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") // Connection settings config.streamingMode = .streaming config.startOnline = true // Event configuration config.sendEvents = true config.eventCapacity = 100 config.eventFlushInterval = 30 // Polling backup config.flagPollingInterval = 300 config.backgroundFlagPollingInterval = 3600 // Background support config.enableBackgroundUpdates = false // Privacy config.allContextAttributesPrivate = false config.privateContextAttributes = [ Reference("email"), Reference("phone") ] // Performance config.connectionTimeout = 10 // Debug #if DEBUG config.debugMode = true #endif let context = try LDContextBuilder(key: "user-123").build() LDClient.start(config: config, context: context) ``` -------------------------------- ### Enable REPORT HTTP Method Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/09-networking.md Configure the SDK to use the REPORT HTTP method instead of GET for flag requests. This is useful when network policies forbid GET with a request body or strict firewalls require the REPORT method. ```swift var config = LDConfig(mobileKey: "YOUR_KEY") config.useReport = true ``` -------------------------------- ### Method Documentation Template Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/INDEX.md This template illustrates the standard structure for documenting individual methods within the SDK. It includes the method signature, a description, parameter details, return value information, and a realistic usage example. ```markdown ### `methodName(param1:param2:)` Description of what the method does. ```swift public func methodName(param1: Type, param2: Type) -> ReturnType ``` **Parameters** | Name | Type | Required | Default | Description | |------|------|----------|---------|-------------| | param1 | Type | Yes | — | What this param does | **Returns** Description of return value **Example** ```swift // Realistic usage example ``` ``` -------------------------------- ### Get Primary LDClient Instance Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/01-ldclient-initialization.md Retrieve the main LDClient singleton. Use this when you only need one instance of the SDK. ```swift public static func get() -> LDClient? ``` ```swift if let client = LDClient.get() { let flagValue = client.boolVariation(forKey: "my-flag", defaultValue: false) } ``` -------------------------------- ### Configure SDK to Start Offline Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/05-ldconfig.md Set `startOnline` to `false` to prevent the SDK from connecting to LaunchDarkly services on startup. You must manually call `setOnline(true)` to initiate a connection. ```swift var config = LDConfig(mobileKey: "YOUR_KEY") config.startOnline = false // Start offline, connect later LDClient.start(config: config) // SDK starts offline LDClient.get()?.setOnline(true) // Manually go online ``` -------------------------------- ### Configure LaunchDarkly iOS SDK Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/10-events-analytics.md Configure the SDK with your mobile key, event settings, evaluation tracking, privacy preferences, and diagnostic options. Start the client with a context and track custom events or evaluate flags. ```swift import LaunchDarkly var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") // Event configuration config.sendEvents = true config.eventCapacity = 200 config.eventFlushInterval = 30 config.enableCompression = true // Evaluation tracking config.evaluationReasons = false // Only send reasons for *Detail() methods // Privacy config.allContextAttributesPrivate = false config.privateContextAttributes = [ Reference("ssn"), Reference("creditCard") ] // Diagnostics config.diagnosticOptOut = false config.diagnosticRecordingInterval = 900 // 15 minutes // Start SDK let context = try LDContextBuilder(key: "user-123").build() LDClient.start(config: config, context: context) // Track custom events LDClient.get()?.track(key: "app-launched") LDClient.get()?.track( key: "feature-used", data: ["featureName": "dashboard"], metricValue: 1.0 ) // Flag evaluations automatically generate events let newUI = LDClient.get()?.boolVariation(forKey: "new-ui", defaultValue: false) ?? false ``` -------------------------------- ### Online/Offline Configuration Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/05-ldconfig.md Controls whether the SDK attempts to connect to LaunchDarkly services upon initialization. By default, the SDK starts online. ```APIDOC ## Online/Offline Configuration ### Description Controls whether the SDK attempts to connect to LaunchDarkly services upon initialization. By default, the SDK starts online. ### Property `startOnline: Bool` ### Default `true` ### Usage If `false`, the SDK will not attempt to connect to LaunchDarkly services until `setOnline(true)` is called. ### Example ```swift var config = LDConfig(mobileKey: "YOUR_KEY") config.startOnline = false // Start offline, connect later LDClient.start(config: config) // SDK starts offline LDClient.get()?.setOnline(true) // Manually go online ``` ``` -------------------------------- ### Install iOS Client SDK with Swift Package Manager Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/README.md Add the LaunchDarkly iOS Client SDK to your project using Swift Package Manager. Ensure you use the correct version. ```swift .package(url: "https://github.com/launchdarkly/ios-client-sdk.git", .upToNextMajor(from: "11.2.0")) ``` -------------------------------- ### Observe Flag Changes and Apply Theme Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/03-flag-observers.md Example of observing a specific flag ('theme-flag') and reacting to its changes. It demonstrates how to safely cast `oldValue` and `newValue` to a `String` and apply a new theme based on the updated value. ```swift LDClient.get()?.observe("theme-flag", owner: self) { changedFlag in if let oldTheme = changedFlag.oldValue as? String, let newTheme = changedFlag.newValue as? String { print("Theme changed from \(oldTheme) to \(newTheme)") applyTheme(newTheme) } } ``` -------------------------------- ### Example Custom Logging Plugin Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/07-hooks-and-plugins.md A custom logging plugin that formats and prints log messages with timestamps and levels. Implement the `log` method to customize log output. ```swift class CustomLogPlugin: Plugin { var metadata: PluginMetadata { return PluginMetadata( name: "custom-log-plugin", version: "1.0.0", custom: nil ) } func configure(context: LDContext) -> Bool { print("Custom logging plugin initialized") return true } func log(message: String, level: String) { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let timestamp = formatter.string(from: Date()) print("[\(timestamp)] [\(level)] \(message)") } } ``` -------------------------------- ### Custom Event Examples Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/10-events-analytics.md Illustrates various ways to use the `track` function for custom events, including simple events, events with data, events with a metric value, and events with both data and a metric. ```swift // Simple event LDClient.get()?.track(key: "user-signup") // Event with data LDClient.get()?.track( key: "purchase", data: [ "item": "premium-plan", "amount": 99.99, "currency": "USD" ] ) // Event with metric value LDClient.get()?.track( key: "page-load-time", metricValue: 245.5 // milliseconds ) // Event with both data and metric LDClient.get()?.track( key: "api-call", data: ["endpoint": "/users", "method": "GET"], metricValue: 125.0 // milliseconds ) ``` -------------------------------- ### Hook Execution Order Example Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/07-hooks-and-plugins.md Illustrates the execution order of 'beforeEvaluation' and 'afterEvaluation' hooks for a flag evaluation. 'beforeEvaluation' hooks run in configuration order, followed by evaluation, and then 'afterEvaluation' hooks run in reverse configuration order. ```swift // With three hooks A, B, C: // beforeEvaluation: A → B → C → [evaluation] → afterEvaluation: C → B → A ``` -------------------------------- ### Get Secondary LDClient Instance by Environment Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/01-ldclient-initialization.md Retrieve a specific LDClient instance for a given environment name. This is useful for multi-environment SDK configurations. ```swift public static func get(environment: String) -> LDClient? ``` ```swift // In a multi-environment setup if let prodClient = LDClient.get(environment: "production") { let value = prodClient.boolVariation(forKey: "flag", defaultValue: false) } ``` -------------------------------- ### Validate SDK Configuration Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/08-error-handling.md Ensure the 'mobileKey' is provided before starting the SDK. Invalid configurations like short timeouts are clamped to minimums in production, while issues like an empty 'mobileKey' will cause 'LDClient.start()' to return nil. ```swift var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") config.connectionTimeout = 1 // Too short // In debug mode, this is allowed // In production, would be increased to minimum if !config.mobileKey.isEmpty { let client = LDClient.start(config: config) if client != nil { print("SDK started successfully") } else { print("Failed to start SDK: check mobile key") } } else { print("Configuration error: mobile key is required") } ``` -------------------------------- ### Configure Multi-Environment Access Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/05-ldconfig.md Use `secondaryMobileKeys` to configure multiple LaunchDarkly environments in a single app. This allows starting the primary client and accessing secondary clients by environment name. ```swift var config = LDConfig(mobileKey: "production-key") config.secondaryMobileKeys = [ "staging": "staging-key", "testing": "testing-key" ] // Start primary (production) client LDClient.start(config: config) // Access secondary clients let stagingClient = LDClient.get(environment: "staging") let testingClient = LDClient.get(environment: "testing") ``` -------------------------------- ### Configure Background Updates and Polling Interval Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/11-caching-offline.md Configure background updates and set a custom polling interval for background flag retrieval. This example sets background updates to true and a 10-minute polling interval. ```swift var config = LDConfig(mobileKey: "YOUR_KEY") config.enableBackgroundUpdates = true config.backgroundFlagPollingInterval = 600 // 10 minutes ``` -------------------------------- ### Creating Contexts with Different Kinds Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/04-context-api.md Provides examples of creating LDContext objects using LDContextBuilder with the built-in '.user' kind and custom kinds like '.custom("device")' and '.custom("my-custom-kind")'. ```swift let userContext = try LDContextBuilder(key: "user-123") .kind(.user) .build() let deviceContext = try LDContextBuilder(key: "device-456") .kind(.custom("device")) .build() let customContext = try LDContextBuilder(key: "custom-789") .kind(.custom("my-custom-kind")) .build() ``` -------------------------------- ### Monitor Network Connectivity Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/09-networking.md Use the system's Network framework to monitor network availability and inform the SDK whether to be online or offline. Ensure the monitor is started on a background queue. ```swift import Network let monitor = NWPathMonitor() monitor.pathUpdateHandler = { path in if path.status == .satisfied { // Network is available LDClient.get()?.setOnline(true) } else { // Network is unavailable LDClient.get()?.setOnline(false) } } let queue = DispatchQueue(label: "NetworkMonitor") monitor.start(queue: queue) ``` -------------------------------- ### Watch Complication Example Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/12-platform-specific.md Implement a watchOS complication data source to display feature flag status. It recommends updates based on the polling interval and checks flag variations to determine content. ```swift class ComplicationController: NSObject, CLKComplicationDataSource { func getNextRequestedUpdateDate(handler: @escaping (Date?) -> Void) { // Recommend update based on polling interval let nextUpdate = Date().addingTimeInterval(600) // 10 minutes handler(nextUpdate) } func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) { let enabled = LDClient.get()?.boolVariation(forKey: "complication-enabled", defaultValue: true) ?? true if enabled { // Show complication let template = CLKSimpleTextProvider(text: "Feature ON") let entry = CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template) handler(entry) } else { handler(nil) } } } ``` -------------------------------- ### Initialize LDClient with Configuration and Context Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/01-ldclient-initialization.md Use this method to initialize the LDClient singleton. Provide your mobile key in the configuration and optionally define a user context. A completion closure can be provided to execute code after the SDK has fetched initial flag values or encountered an error. The SDK creates a default user context if none is provided. ```swift import LaunchDarkly // Create a basic configuration var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") config.baseUrl = URL(string: "https://app.launchdarkly.com")! // Create a context representing the user let context = try LDContextBuilder(key: "user-123") .name("Alice Smith") .build() // Start the client LDClient.start(config: config, context: context) { print("SDK initialized with flag values") } // Access the client from anywhere in your app if let client = LDClient.get() { let showFeature = client.boolVariation(forKey: "new-feature", defaultValue: false) } ``` -------------------------------- ### Evaluate Boolean Flag with Reason Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Get detailed information about a boolean flag evaluation, including the reason for the evaluation. ```swift let detail = LDClient.get()?.boolVariationDetail(forKey: "feature-flag", defaultValue: false) if let reason = detail?.reason, case .string(let kind) = reason["kind"] { print("Evaluation reason: \(kind)") } ``` -------------------------------- ### Implement Identity Change Hook Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/07-hooks-and-plugins.md Example implementation of an identify hook. Use this to react to context changes before or after an identify operation. ```swift class IdentityChangeHook: Hook { func beforeIdentify(seriesContext: IdentifySeriesContext, seriesData: EvaluationSeriesData) -> EvaluationSeriesData { print("Switching context to: \(seriesContext.context.key)") return seriesData } func afterIdentify(seriesContext: IdentifySeriesContext, seriesData: EvaluationSeriesData) -> EvaluationSeriesData { print("Context switched and flags updated") return seriesData } } ``` -------------------------------- ### Initialize LDConfig with Minimal Configuration Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/05-ldconfig.md Initializes LDConfig with only the required mobile key. Default URLs will be used. ```swift // Minimal configuration var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") ``` -------------------------------- ### Evaluate String Flag Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Get the string value of a feature flag. Provide a default value if the flag is not found or an error occurs. ```swift let theme = LDClient.get()?.stringVariation(forKey: "theme", defaultValue: "light") ?? "light" ``` -------------------------------- ### Evaluate Boolean Flag Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Get the boolean value of a feature flag. Provide a default value if the flag is not found or an error occurs. ```swift let enabled = LDClient.get()?.boolVariation(forKey: "feature-flag", defaultValue: false) ?? false if enabled { showNewFeature() } ``` -------------------------------- ### LDClient Initialization Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/README.md Initializes the LaunchDarkly SDK with configuration and a user context. The SDK instance can then be accessed globally. ```APIDOC ## LDClient.start() ### Description Initializes the LaunchDarkly SDK with the provided configuration and user context. This method should be called once during application startup. ### Method `static func start(config: LDConfig, context: LDContext) ### Parameters - **config** (`LDConfig`): The SDK configuration, including the mobile key. - **context** (`LDContext`): The user or entity context for flag evaluation. ### Usage ```swift import LaunchDarkly var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") let context = try LDContextBuilder(key: "user-123").build() LDClient.start(config: config, context: context) ``` ## LDClient.get() ### Description Retrieves the singleton instance of the `LDClient`. This method can be called after `start()` has been successfully invoked. ### Method `static func get() -> LDClient?` ### Return Value An optional `LDClient` instance if the SDK has been initialized, otherwise `nil`. ### Usage ```swift let client = LDClient.get() ``` ``` -------------------------------- ### Event Collection Endpoint Request Body Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/09-networking.md Example structure for the request body sent to the Event Collection Endpoint, which submits analytics events. ```json [ { "kind": "feature", "key": "flag-key", "user": { "key": "user-123" }, "variation": 0, "value": true, "version": 123, "timestamp": 1234567890 }, { "kind": "custom", "key": "custom-event", "user": { "key": "user-123" }, "data": { "action": "completed" }, "timestamp": 1234567890 } ] ``` -------------------------------- ### Module Import and Basic Usage Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Import the LaunchDarkly module and access core classes and types for client initialization and flag evaluation. ```swift import LaunchDarkly // Access classes let config = LDConfig(mobileKey: "key") let context = try LDContextBuilder(key: "user-1").build() let client = LDClient.get() // Access types let flagValue: LDValue = .string("test") let flagKey: LDFlagKey = "my-flag" let detail: LDEvaluationDetail = ... ``` -------------------------------- ### Building a Custom Organization Context Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/04-context-api.md Illustrates creating a custom context for an organization, including setting a specific attribute like 'plan' with a string value. ```swift let orgContext = try LDContextBuilder(key: "org-456") .kind(.custom("organization")) .set("plan", value: .string("enterprise")) .build() ``` -------------------------------- ### Get Primary LDClient Instance Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/01-ldclient-initialization.md Retrieves the main singleton instance of the LDClient. This is the most common way to access the client if you are not using multi-environment support. ```APIDOC ## `LDClient.get()` ### Description Returns the primary LDClient singleton instance. ### Method Signature ```swift public static func get() -> LDClient? ``` ### Returns The primary `LDClient` instance if one has been started, otherwise `nil`. ### Example ```swift if let client = LDClient.get() { let flagValue = client.boolVariation(forKey: "my-flag", defaultValue: false) } ``` ``` -------------------------------- ### Configure LaunchDarkly SDK Settings Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/README.md Set essential SDK configurations like streaming mode, background updates, event tracking, and privacy controls. ```swift // Most important settings var config = LDConfig(mobileKey: "YOUR_KEY") config.streamingMode = .streaming // Real-time or polling config.enableBackgroundUpdates = true // Support background config.sendEvents = true // Analytics enabled config.privateContextAttributes = [...] // Privacy control config.eventCapacity = 100 // Queue size config.eventFlushInterval = 30 // Send events every 30s config.flagPollingInterval = 300 // Polling interval (5m) ``` -------------------------------- ### Evaluate Custom Type Flag Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Get a custom type value for a feature flag. The custom type must conform to Codable and LDValueConvertible. ```swift struct UserConfig: Codable, LDValueConvertible { let theme: String let notificationsEnabled: Bool func toLDValue() -> LDValue { return ["theme": .string(theme), "notificationsEnabled": .bool(notificationsEnabled)] } } let userConfig = LDClient.get()?.variation( forKey: "user-config", defaultValue: UserConfig(theme: "light", notificationsEnabled: true) ) ?? UserConfig(theme: "light", notificationsEnabled: true) ``` -------------------------------- ### Building a User Context Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/04-context-api.md Shows how to construct a user context using `LDContextBuilder`. This includes setting the key, name, and kind for the user. ```swift let userContext = try LDContextBuilder(key: "user-123") .name("Alice") .kind(.user) .build() ``` -------------------------------- ### Evaluate JSON Flag Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Get the JSON value of a feature flag. Provide a default JSON value if the flag is not found or an error occurs. ```swift let config = LDClient.get()?.jsonVariation(forKey: "app-config", defaultValue: .null) ?? .null if case .object(let configObj) = config { // Access nested values } ``` -------------------------------- ### Create Basic User Context Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/04-context-api.md Use LDContextBuilder to create a basic user context with a key and name. This context can then be used to initialize the LDClient. ```swift let context = try LDContextBuilder(key: "user-123") .name("Alice Johnson") .build() LDClient.start(config: config, context: context) ``` -------------------------------- ### Custom LDValueConvertible Implementation Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/06-types-and-models.md Provides a custom implementation of `LDValueConvertible` for a `UserPreferences` struct. This example shows how to serialize custom data into an `LDValue` for use with the SDK. ```swift struct UserPreferences: Codable, LDValueConvertible { let theme: String let notifications: Bool let language: String func toLDValue() -> LDValue { return [ "theme": .string(theme), "notifications": .bool(notifications), "language": .string(language) ] } } // Use in variation methods let prefs = LDClient.get()?.variation( forKey: "user-prefs", defaultValue: UserPreferences(theme: "light", notifications: true, language: "en") ) ``` -------------------------------- ### Implement Event Enrichment Hook Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/07-hooks-and-plugins.md Example implementation of a track hook for event enrichment. This hook adds a timestamp and user ID to event data before tracking. ```swift class EventEnrichmentHook: Hook { func beforeTrack(seriesContext: TrackSeriesContext, seriesData: EvaluationSeriesData) -> EvaluationSeriesData { // Add timestamp and user info var data = seriesContext.data ?? .object([:]) if case .object(var obj) = data { obj["timestamp"] = .string(ISO8601DateFormatter().string(from: Date())) obj["userId"] = .string(seriesContext.context.key) data = .object(obj) seriesData.data["enrichedData"] = data } return seriesData } func afterTrack(seriesContext: TrackSeriesContext, seriesData: EvaluationSeriesData) -> EvaluationSeriesData { print("Event tracked: \(seriesContext.eventKey)") return seriesData } } ``` -------------------------------- ### Example Feature Flag Evaluation Event Generation Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/10-events-analytics.md Demonstrates how a call to a variation method like `boolVariation()` automatically generates a feature flag evaluation event. ```swift // This generates a feature flag evaluation event let showFeature = LDClient.get()?.boolVariation( forKey: "new-dashboard", defaultValue: false ) ?? false ``` -------------------------------- ### LaunchDarkly SDK Configuration Options Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Customize SDK behavior including connection modes, event settings, privacy controls, performance tuning, and debug mode. ```swift var config = LDConfig(mobileKey: "YOUR_KEY") // Connection config.streamingMode = .streaming // .streaming or .polling config.enableBackgroundUpdates = false // true for background flag updates // Events config.sendEvents = true // Send analytics to LaunchDarkly config.eventCapacity = 100 // Queue size config.eventFlushInterval = 30 // Seconds between flushes // Privacy config.allContextAttributesPrivate = false config.privateContextAttributes = [Reference("email"), Reference("ssn")] // Performance config.flagPollingInterval = 300 // 5 minutes config.backgroundFlagPollingInterval = 3600 // 60 minutes config.connectionTimeout = 10 // 10 seconds // Debug #if DEBUG config.debugMode = true #endif ``` -------------------------------- ### Request Configuration - HTTP Method Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/05-ldconfig.md Configure the HTTP method used for flag requests. By default, GET is used, but you can switch to REPORT for enhanced network security. ```APIDOC ## Request Configuration - HTTP Method ### Property - **useReport** (Bool) - `false` (default): Set to `true` to use the HTTP REPORT method instead of GET for flag requests. ### Description When `true`, the SDK uses the HTTP REPORT method for streaming and flag requests instead of GET. This can be useful when you have strict network security policies. ### Example ```swift var config = LDConfig(mobileKey: "YOUR_KEY") config.useReport = true ``` ``` -------------------------------- ### Flag Evaluation Endpoint Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/09-networking.md Retrieves current flag values for a given context. This endpoint can be accessed via GET or REPORT methods depending on the `useReport` setting. ```APIDOC ## Endpoints ### Flag Evaluation Endpoint Retrieves current flag values for a context. ``` Method: GET or REPORT (depending on useReport setting) Path: /meval Content-Type: application/json Accept: application/json ``` **Request Parameters** - Mobile key in Authorization header - Context JSON in request body (for REPORT) or URL-encoded (for GET) **Response** ```json { "flag-key-1": { "value": true, "variation": 0, "version": 123, "trackEvents": false, "reason": { "kind": "ON" } }, "flag-key-2": { "value": "variation-a", "variation": 1, "version": 456, "trackEvents": true } } ``` ``` -------------------------------- ### Add LaunchDarkly to Carthage Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/README.md Specify the LaunchDarkly SDK in your Cartfile for integration with Carthage. This allows Carthage to manage the SDK as a dependency. ```ogdl github "launchdarkly/ios-client-sdk" ~> 11.2 ``` -------------------------------- ### Evaluate String Flag with Default Value Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/02-flag-variations.md Use `stringVariation` to get a string flag's value. Provide a default value to be returned if the flag is not found or unavailable. ```swift let theme = LDClient.get()?.stringVariation(forKey: "ui-theme", defaultValue: "light") ?? "light" applyTheme(theme) // "light", "dark", "auto", etc. ``` -------------------------------- ### Evaluate Double Flag - iOS Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/02-flag-variations.md Use `doubleVariation` to get the evaluated floating-point value of a flag. Provide a default value to be returned if the flag is unavailable or the type does not match. ```swift let discountRate = LDClient.get()?.doubleVariation(forKey: "discount-percentage", defaultValue: 0.0) ?? 0.0 let finalPrice = basePrice * (1.0 - discountRate) ``` -------------------------------- ### Evaluate Integer Flag - iOS Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/02-flag-variations.md Use `intVariation` to get the evaluated integer value of a flag. Provide a default value to be returned if the flag is unavailable or the type does not match. ```swift let maxConnections = LDClient.get()?.intVariation(forKey: "max-connections", defaultValue: 5) ?? 5 ``` -------------------------------- ### Accessing Context Information Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/04-context-api.md Demonstrates how to retrieve and access information from the current context using `LDClient.get()?.context`. ```APIDOC ## Accessing Context Information ### Retrieving Current Context Use `LDClient.get()?.context` to access the current context and its properties. ```swift if let context = LDClient.get()?.context { print("Context key: \(context.key)\)") print("Context kind: \(context.kind)\)") print("Is anonymous: \(context.anonymous)\)") if let email = context.attributes["email"] { print("Email: \(email)\)") } } ``` ``` -------------------------------- ### Get Current LDContext Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/01-ldclient-initialization.md Access the `context` property to retrieve the `LDContext` object representing the current user or multi-context. This is useful for inspecting the active user's attributes. ```swift public private(set) var context: LDContext ``` ```swift if let currentContext = LDClient.get()?.context { print("Current user key: \(currentContext.key)") } ``` -------------------------------- ### Multi-Environment Configuration Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/05-ldconfig.md Configure secondary mobile keys for additional environments, allowing the use of multiple LaunchDarkly environments within a single application. ```APIDOC ## Multi-Environment Configuration ### Description Allows configuring multiple LaunchDarkly environments in a single app by providing secondary mobile keys. ### Property `secondaryMobileKeys: [String: String]` ### Example ```swift var config = LDConfig(mobileKey: "production-key") config.secondaryMobileKeys = [ "staging": "staging-key", "testing": "testing-key" ] // Start primary (production) client LDClient.start(config: config) // Access secondary clients let stagingClient = LDClient.get(environment: "staging") let testingClient = LDClient.get(environment: "testing") ``` ``` -------------------------------- ### Get Environment-Specific LDClient Instance Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/01-ldclient-initialization.md Retrieves a specific LDClient instance for a given environment name. This is useful for applications that need to manage multiple LaunchDarkly environments simultaneously. ```APIDOC ## `LDClient.get(environment:)` ### Description Returns a secondary LDClient instance for a specific environment (multi-environment SDK support). ### Method Signature ```swift public static func get(environment: String) -> LDClient? ``` ### Parameters #### Path Parameters - **environment** (`String`) - Required - The environment name. Use `LDConfig.Constants.primaryEnvironmentName` for the default environment. ### Returns The `LDClient` instance for the specified environment, or `nil` if not found. ### Example ```swift // In a multi-environment setup if let prodClient = LDClient.get(environment: "production") { let value = prodClient.boolVariation(forKey: "flag", defaultValue: false) } ``` ``` -------------------------------- ### Get Boolean Flag Value Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/02-flag-variations.md Use this method to retrieve the direct boolean value of a feature flag. Provide a default value to be returned if the flag is unavailable or of an unexpected type. ```swift let showNewUI = LDClient.get()?.boolVariation(forKey: "new-dashboard", defaultValue: false) ?? false if showNewUI { showNewDashboard() } else { showLegacyDashboard() } ``` -------------------------------- ### Configure and Identify with Multi-Context Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/README.md Build and identify with multiple user contexts, including custom kinds, for advanced targeting scenarios. ```swift var builder = LDMultiContextBuilder() try builder.add(LDContextBuilder(key: "user-123").build()) try builder.add(LDContextBuilder(key: "org-456").kind(.custom("organization")).build()) let multiContext = try builder.build() LDClient.get()?.identify(context: multiContext) ``` -------------------------------- ### Check Minimum OS Version Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/12-platform-specific.md Before initializing the LaunchDarkly SDK, check if the current operating system version meets the minimum requirement. This prevents potential issues on older OS versions. ```swift import os let minVersion = OperatingSystemVersion(majorVersion: 13, minorVersion: 0, patchVersion: 0) if ProcessInfo.processInfo.operatingSystemVersion >= minVersion { // Safe to use SDK features LDClient.start(config: config) } else { print("Unsupported OS version") } ``` -------------------------------- ### Testing Offline Mode with Cached Flags Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/11-caching-offline.md Demonstrates how to test the SDK's offline capabilities. It shows setting up the client in online mode, then switching to offline mode to verify that flag variations are served from the local cache. ```swift class TestViewController: UIViewController { func testOfflineMode() { // Set up with online mode first var config = LDConfig(mobileKey: "YOUR_KEY") let context = try LDContextBuilder(key: "test-user").build() LDClient.start(config: config, context: context) { // Flags are now cached // Go offline LDClient.get()?.setOnline(false) { // Now test with cached flags let value = LDClient.get()?.boolVariation( forKey: "test-flag", defaultValue: false ) ?? false // Value comes from cache print("Offline flag value: \(value)") } } } } ``` -------------------------------- ### Configure SDK with Hooks Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/07-hooks-and-plugins.md Configure the LDConfig with an array of hook implementations. Hooks are executed during SDK lifecycle events. ```swift var config = LDConfig(mobileKey: "YOUR_KEY") config.hooks = [ LoggingHook(), CachingHook(), IdentityChangeHook() ] LDClient.start(config: config) ``` -------------------------------- ### Configure Global Private Attributes Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/04-context-api.md Set `privateContextAttributes` in `LDConfig` to define attributes that are always treated as private across all contexts used with the client. This configuration must be set before starting the client. ```swift var config = LDConfig(mobileKey: "YOUR_KEY") config.privateContextAttributes = [ Reference("email"), Reference("ssn"), Reference("payment-info") ] LDClient.start(config: config, context: context) ``` -------------------------------- ### Debug vs. Release Configuration Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/12-platform-specific.md Use preprocessor directives to configure the SDK differently for debug and release builds. Debug builds can have faster polling intervals for testing. ```swift #if DEBUG var config = LDConfig(mobileKey: "YOUR_DEBUG_KEY") config.debugMode = true config.flagPollingInterval = 30 // Faster for testing #else var config = LDConfig(mobileKey: "YOUR_PRODUCTION_KEY") config.debugMode = false config.flagPollingInterval = 300 // Slower for production #endif ``` -------------------------------- ### Initialize LDConfig with Custom URLs Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/05-ldconfig.md Initializes LDConfig and then overrides the default URLs for feature flags, events, and streaming. ```swift // Custom URLs var config = LDConfig(mobileKey: "YOUR_MOBILE_KEY") config.baseUrl = URL(string: "https://app.launchdarkly.com")! config.eventsUrl = URL(string: "https://mobile.launchdarkly.com")! config.streamUrl = URL(string: "https://clientstream.launchdarkly.com")! ``` -------------------------------- ### Get Boolean Flag Value with Evaluation Details Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/02-flag-variations.md Use this method to retrieve a boolean feature flag's value along with its evaluation metadata. This includes the value, variation index, and the reason for evaluation. ```swift let detail = LDClient.get()?.boolVariationDetail(forKey: "feature-flag", defaultValue: false) ?? LDEvaluationDetail(value: false) print("Value: \(detail.value)") print("Reason: \(detail.reason)") // e.g., {"kind": "ON"} or {"kind": "OFF"} print("Variation Index: \(String(describing: detail.variationIndex))") ``` -------------------------------- ### LDContextBuilder Swift API Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/04-context-api.md Defines the structure and methods for building a single-kind LaunchDarkly context. ```swift public struct LDContextBuilder { public init(key: String) public mutating func name(_ name: String?) -> LDContextBuilder public mutating func anonymous(_ anonymous: Bool) -> LDContextBuilder public mutating func addPrivateAttribute(_ reference: Reference) -> LDContextBuilder public mutating func kind(_ kind: Kind) -> LDContextBuilder public mutating func set(_ reference: Reference, value: LDValue) -> LDContextBuilder public mutating func set(_ key: String, value: LDValue) -> LDContextBuilder public func build() throws -> LDContext } ``` -------------------------------- ### LDContextBuilder Basic Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Builds a basic user context using the LDContextBuilder with only a required key. Ensure the key is unique and non-empty. ```swift // Basic let context = try LDContextBuilder(key: "user-123").build() ``` -------------------------------- ### Evaluate JSON Flag with Default Value Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/02-flag-variations.md Use `jsonVariation` to retrieve a JSON feature flag. A default `LDValue` is returned if the flag is not available. The example shows how to safely unwrap and access nested JSON properties. ```swift let configValue = LDClient.get()?.jsonVariation(forKey: "app-config", defaultValue: .null) ?? .null if case .object(let config) = configValue { if let timeout = config["timeout"] { // Use the timeout value } } ``` -------------------------------- ### Configuration Defaults Source: https://github.com/launchdarkly/ios-client-sdk/blob/v11/_autodocs/13-quick-reference.md Default values for LaunchDarkly client configuration. These can be overridden during client initialization. ```swift baseUrl: https://app.launchdarkly.com eventsUrl: https://mobile.launchdarkly.com streamUrl: https://clientstream.launchdarkly.com streamingMode: .streaming flagPollingInterval: 300 seconds (5 minutes) backgroundFlagPollingInterval: 3600 seconds (60 minutes) enableBackgroundUpdates: false sendEvents: true eventCapacity: 100 eventFlushInterval: 30 seconds connectionTimeout: 10 seconds maxCachedContexts: 5 useReport: false evaluationReasons: false allContextAttributesPrivate: false diagnosticOptOut: false diagnosticRecordingInterval: 900 seconds (15 minutes) debugMode: false enableCompression: false autoEnvAttributes: .disabled ```