• Home
  • Integrations
  • SDKs
  • Guides
  • API docs
    No results for ""
    EXPAND ALL

    EDIT ON GITHUB

    iOS SDK reference

    Read time: 4 minutes
    Last edited: Mar 16, 2023
    Version 8 of the iOS SDK replaces users with contexts

    A context is a generalized way of referring to the people, services, machines, or other resources that encounter feature flags in your product. Contexts replace another data object in LaunchDarkly: "users."

    Code samples on this page are from the two most recent SDK versions where they differ. To learn more about upgrading, read the iOS SDK 7.x to 8.0 migration guides for Swift or Objective-C and Best practices for upgrading users to contexts.

    Overview

    This topic documents how to get started with the iOS SDK, and links to reference information on all of the supported features.

    SDK quick links

    LaunchDarkly's SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and sample applications:

    ResourceLocation
    SDK API documentationSDK API docs
    GitHub repositoryios-client-sdk
    Sample applicationsiOS (Objective-C)
    iOS (Swift)
    macOS
    tvOS
    Published moduleCocoaPods
    SDK version compatibility

    The LaunchDarkly iOS SDK, version 4.0.0 and higher, is compatible with applications written in either Swift or Objective-C. The inline code samples include both languages. The SDK is written in Swift.

    Getting started

    After you complete the Getting started process, follow these instructions to start using the LaunchDarkly SDK in your application.

    Including the SDK as a dependency

    The first step is to install the LaunchDarkly SDK as a dependency in your application.

    LaunchDarkly supports multiple methods for installing the SDK:

    • Using the Swift Package Manager
    • Using CocoaPods
    • Using Carthage
    • Installing the SDK manually

    Each method is explained below.

    Using the Swift Package Manager



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

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

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

    //...
    dependencies: [
    .package(url: "https://github.com/launchdarkly/ios-client-sdk.git", .upToNextMinor("8.0.0")),
    ],
    targets: [
    .target(
    name: "YOUR_TARGET",
    dependencies: ["LaunchDarkly"]
    )
    ],
    //...

    Using CocoaPods



    If you use CocoaPods, you can install the SDK by adding the following to your Podfile. To identify the latest version, read the SDK releases page.

    Here is the code to add to your Podfile:

    use_frameworks!
    target 'YourTargetName' do
    pod 'LaunchDarkly', '~> 8.0'
    end

    Using Carthage



    If you use Carthage, you can install the SDK by specifying it in your Cartfile. To identify the latest version, read the SDK releases page.

    Here is the code to include in your Cartfile:

    github "launchdarkly/ios-client" ~> 8.0

    Installing the SDK manually



    For instructions on installing the SDK without CocoaPods or Carthage, read the SDK readme.

    Using the SDK in your application

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

    Importing



    First import the LaunchDarkly client in your application code:

    import LaunchDarkly

    Initializing the SDK



    After importing the SDK, configure and initialize it. Specify your mobile key when configuring the SDK so that your application is authorized to connect to a particular environment within LaunchDarkly. Your mobile key is available in the Projects tab of your Account settings page.

    Never embed a server-side SDK key into a client-side application

    Mobile keys are not secret and you can expose them in your client-side code without risk. However, never embed a server-side SDK key into a client-side application.

    Here is how to specify your mobile key:

    // If you would like the completion to be called even in cases where
    // the SDK is unable to retrieve flags for the context, there is a variant
    // to the start method that takes a maximum time to wait for flag values.
    // This variant notifies the completion whether the operation timed out.
    let config = LDConfig(mobileKey: "mobile-key-123abc")
    let context = LDContextBuilder(key: "context-key-123abc")
    LDClient.start(config: config, context: context, startWaitSeconds: 5) { timedOut in
    if timedOut {
    // The SDK may not have the most recent flags for the configured context
    } else {
    // The SDK has received flags for the configured context
    }
    }

    However, calling blocking code from the main thread in a mobile app is not considered a best practice. The preferred method is loading the client asynchronously.

    Here's how:

    let config = LDConfig(mobileKey: "mobile-key-123abc")
    let context = LDContextBuilder(key: "context-key-123abc")
    LDClient.start(config: config, context: context)
    // If you need to ensure that the most recent flags have been received
    // start supports an optional completion that is triggered when the SDK
    // has retrieved flags for the configured context.
    LDClient.start(config: config, context: context) {
    // Client has received flags for the context
    }
    LDClient must be a singleton

    It's important to make LDClient a singleton for each LaunchDarkly project. The client instance maintains internal state that allows LaunchDarkly to serve feature flags without making any remote requests. Do not instantiate a new client with every request.

    If you have multiple LaunchDarkly projects, you can create one LDClient for each. In this situation, the clients operate independently. For example, they do not share a single connection to LaunchDarkly.

    Retrieving the client instance



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

    let client = LDClient.get()!

    Getting the variation to serve the configured context



    Making feature flags available to this SDK

    You must make feature flags available to mobile SDKs before the SDK can evaluate those flags. If an SDK tries to evaluate a feature flag that is not available, the context will receive the default value for that flag.

    To make a flag available to this SDK, check the SDKs using Mobile key checkbox during flag creation, or on the flag's Settings tab. To make all of a project's flags available to this SDK by default, check the SDKs using Mobile key checkbox in your project Settings.

    You can use client to check which variation a particular context will receive for a given feature flag.

    Here's how:

    let showFeature = client.boolVariation(forKey: "flag-key", defaultValue: false)
    if showFeature {
    // Application code to show the feature
    else {
    // The code to run if the feature is off
    }

    Background fetch

    When the app is backgrounded, the SDK does not receive real-time events.

    Unlike other mobile SDKs, the iOS SDK does not support background fetch, so devices on the iOS operating system will not fetch flags from the background. However, devices on MacOS will update flag values opportunistically, according to the iOS SDK standard background polling defaults.

    To change the background polling default for flags in your app, add the following code in your LDConfig:

    var ldConfig = LDConfig(mobileKey: "mobile-key-123abc")
    ldConfig.backgroundFlagPollingInterval = 3600

    Shutting down

    Shut down the client when your application terminates. To learn more, read Shutting down.

    Data collection

    The data collected by the iOS SDK persists until the number of cached contexts exceeds a limit. When you call identify, the number of cached contexts increments. Eventually, the number of cached contexts exceeds maxCachedContexts. When that happens, the SDK deletes context data in excess of maxCachedContext, starting with the oldest context first.

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

    Supported features

    This SDK supports the following features: