Set up iOS SDK

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

Install the package

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

Initialize the SDK for feature management

iOS SDK initialization
import LaunchDarkly
// This is your mobile key.
let config = LDConfig(mobileKey: "YOUR_MOBILE_KEY", autoEnvAttributes: .enabled)
// A "context" is a data object representing users, devices, organizations, and other entities.
let contextBuilder = LDContextBuilder(key: "EXAMPLE_CONTEXT_KEY")
guard case .success(let context) = contextBuilder.build()
else { return }
LDClient.start(config: config, context: context, startWaitSeconds: 5) { timedOut in
if timedOut {
print("SDK didn't initialize in 5 seconds. SDK is still running and trying to get latest flags.")
} else {
print("SDK successfully initialized with the latest flags")
}
}
print("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
import LaunchDarkly
// Call this once from your app startup (e.g. application(_:didFinishLaunchingWithOptions:)).
// You can't invoke LDClient.start() at the top level in Swift — wrap it in a function.
func startLaunchDarkly() {
// This is your mobile key.
let config = LDConfig(mobileKey: "YOUR_MOBILE_KEY", autoEnvAttributes: .enabled)
// A "context" is a data object representing users, devices, organizations, and other entities.
var contextBuilder = LDContextBuilder(key: "EXAMPLE_CONTEXT_KEY")
contextBuilder.trySetValue("email", .string("EXAMPLE_EMAIL"))
guard case .success(let context) = contextBuilder.build() else { return }
LDClient.start(config: config, context: context, startWaitSeconds: 5) { timedOut in
if timedOut {
print("SDK didn't initialize in 5 seconds. SDK is still running and trying to get latest flags.")
} else {
print("SDK successfully initialized with the latest flags")
}
}
}
// Call trackMetric when a metric action occurs in your app —
// a tap, a form submit, a screen view, a custom event, whatever your metric measures.
func trackMetric(metricKey: String, data: LDValue = .null) {
let client = LDClient.get()!
client.track(key: metricKey, data: data)
}

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.