Set up iOS SDK

Install and initialize the LaunchDarkly iOS SDK to start evaluating feature flags in your application.

Install the package

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

Initialize the SDK for feature management

iOS SDK initialization
1import LaunchDarkly
2
3// This is your mobile key.
4let config = LDConfig(mobileKey: "YOUR_MOBILE_KEY", autoEnvAttributes: .enabled)
5
6// A "context" is a data object representing users, devices, organizations, and other entities.
7let contextBuilder = LDContextBuilder(key: "EXAMPLE_CONTEXT_KEY")
8guard case .success(let context) = contextBuilder.build()
9else { return }
10
11LDClient.start(config: config, context: context, startWaitSeconds: 5) { timedOut in
12 if timedOut {
13 print("SDK didn't initialize in 5 seconds. SDK is still running and trying to get latest flags.")
14 } else {
15 print("SDK successfully initialized with the latest flags")
16 }
17}
18
19print("SDK started.")

Initialize the SDK for feature management and Experimentation

If you want to use the LaunchDarkly Experimentation feature, include a track call in your initialization code:

iOS SDK initialization for Experimentation
1import LaunchDarkly
2
3// Call this once from your app startup (e.g. application(_:didFinishLaunchingWithOptions:)).
4// You can't invoke LDClient.start() at the top level in Swift — wrap it in a function.
5func startLaunchDarkly() {
6 // This is your mobile key.
7 let config = LDConfig(mobileKey: "YOUR_MOBILE_KEY", autoEnvAttributes: .enabled)
8
9 // A "context" is a data object representing users, devices, organizations, and other entities.
10 var contextBuilder = LDContextBuilder(key: "EXAMPLE_CONTEXT_KEY")
11 contextBuilder.trySetValue("email", .string("EXAMPLE_EMAIL"))
12 guard case .success(let context) = contextBuilder.build() else { return }
13
14 LDClient.start(config: config, context: context, startWaitSeconds: 5) { timedOut in
15 if timedOut {
16 print("SDK didn't initialize in 5 seconds. SDK is still running and trying to get latest flags.")
17 } else {
18 print("SDK successfully initialized with the latest flags")
19 }
20 }
21}
22
23// Call trackMetric when a metric action occurs in your app —
24// a tap, a form submit, a screen view, a custom event, whatever your metric measures.
25func trackMetric(metricKey: String, data: LDValue = .null) {
26 let client = LDClient.get()!
27 client.track(key: metricKey, data: data)
28}

You can find your server-side SDK keys, mobile keys, and client-side ID on the SDK keys page under Settings.

To learn more, read Initialize the client in the iOS SDK reference guide.