Set up iOS SDK

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 let contextBuilder = LDContextBuilder(key: "EXAMPLE_CONTEXT_KEY")
11 guard case .success(let context) = contextBuilder.build() else { return }
12
13 LDClient.start(config: config, context: context, startWaitSeconds: 5) { timedOut in
14 if timedOut {
15 print("SDK didn't initialize in 5 seconds. SDK is still running and trying to get latest flags.")
16 } else {
17 print("SDK successfully initialized with the latest flags")
18 }
19 }
20}
21
22// Call trackMetric when a metric action occurs in your app —
23// a tap, a form submit, a screen view, a custom event, whatever your metric measures.
24func trackMetric(metricKey: String, data: LDValue = .null) {
25 let client = LDClient.get()!
26 client.track(key: metricKey, data: data)
27}

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.