OpenFeature Swift Provider
Introduction
The OpenFeature Swift Provider is intended to be used in combination with the OpenFeature Swift SDK in Apple platform applications. The provider wraps the ConfigDirector Swift SDK.
| Platform | Minimum |
|---|---|
| iOS / iPadOS | 15.0 |
| macOS | 12.0 |
| tvOS | 15.0 |
| watchOS | 8.0 |
Building it requires Swift 6.0 or newer and version 0.6.0 or newer of the OpenFeature Swift SDK. The provider is Sendable, so it can be registered from any task or actor.
Config evaluation is synchronous and reads config state the provider already holds in memory, which is what makes it safe to call from a SwiftUI body. Telemetry about those evaluations is aggregated and reported on its own task, so evaluating a config never waits on the network.
Installation
The provider is distributed through Swift Package Manager from its repository: https://github.com/ConfigDirector/configdirector-swift-openfeature-provider
The ConfigDirector Swift SDK is included as a transitive dependency. The OpenFeature Swift SDK has to be added alongside the provider, since your application imports it to evaluate flags.
# In Xcode, go to File -> Add Package Dependencies... and enter the package URL:
https://github.com/ConfigDirector/configdirector-swift-openfeature-provider
dependencies: [
.package(url: "https://github.com/ConfigDirector/configdirector-swift-openfeature-provider", from: "0.1.0"),
.package(url: "https://github.com/open-feature/swift-sdk", from: "0.6.0"),
],
targets: [
.target(
name: "YourTarget",
dependencies: [
.product(name: "ConfigDirectorOpenFeatureProvider", package: "configdirector-swift-openfeature-provider"),
.product(name: "OpenFeature", package: "swift-sdk"),
]
),
]
Configure and initialize the client
- Create an instance of the provider using your client SDK key. You can retrieve a client SDK key for each environment under
SDK Keysin the dashboard's navigation panel. - Set the OpenFeature provider, along with the initial evaluation context.
- Get a client instance from OpenFeature.
import ConfigDirectorOpenFeatureProvider
import OpenFeature
let provider = try ConfigDirectorProvider(clientSDKKey: "YOUR-CLIENT-SDK-KEY")
await OpenFeatureAPI.shared.setProviderAndWait(
provider: provider,
initialContext: ImmutableContext(targetingKey: "user-123")
)
let client = OpenFeatureAPI.shared.getClient()
The initializer throws a ConfigDirectorError in only two cases, both of which are programming errors rather than runtime conditions: missingClientSDKKey when the key is blank, and invalidBaseURL when a custom base URL is not absolute. Connection failures are not thrown.
setProviderAndWait returns once the initial config state arrives or the configured timeout elapses. When it times out, the provider reports the error status and keeps connecting in the background, then reports ready as soon as config state arrives. Until then, flags resolve to their default values.
Most applications register the provider once during startup and let it live for the lifetime of the app. In a SwiftUI app that usually means doing so from the App:
import ConfigDirectorOpenFeatureProvider
import OpenFeature
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.task {
guard let provider = try? ConfigDirectorProvider(clientSDKKey: "YOUR-CLIENT-SDK-KEY") else { return }
await OpenFeatureAPI.shared.setProviderAndWait(
provider: provider,
initialContext: ImmutableContext(targetingKey: "user-123")
)
}
}
}
}
connection options of the Swift SDK to manage that yourself instead.Additional configuration options
Additional configuration options can be passed into the provider as ConfigDirectorClientOptions in the optional second argument of the initializer. The types that configure the underlying client are exported from the provider's module, so configuring it needs no second import.
For example, the metadata can be provided like this:
import ConfigDirectorOpenFeatureProvider
let provider = try ConfigDirectorProvider(
clientSDKKey: "YOUR-CLIENT-SDK-KEY",
options: ConfigDirectorClientOptions(
metadata: ConfigDirectorMetaContext(
appName: "YOUR-APP-NAME",
appVersion: "1.0.2"
)
)
)
The provider accepts the same metadata, connection and logger options as the Swift SDK client, refer to the additional configuration options section of the Swift SDK for a full list.
Shut down
The OpenFeature Swift SDK does not shut providers down. The provider closes its connection, and reports whatever telemetry is left, when it is released, which happens after OpenFeatureAPI.shared.clearProvider() as long as you hold no other reference to it. To close it while you still hold one, call provider.close(). The provider cannot be used afterwards.
Retrieve config values
To retrieve config values, use the OpenFeature client:
let booleanValue = client.getBooleanValue(key: "my-config-key", defaultValue: false)
let stringValue = client.getStringValue(key: "my-string-config-key", defaultValue: "Default")
Each OpenFeature getter maps to a ConfigDirector config type:
| OpenFeature getter | ConfigDirector config value |
|---|---|
getBooleanValue | Boolean |
getStringValue | String or enum |
getIntegerValue, getDoubleValue | Number |
getObjectValue | JSON object or JSON array |
getIntegerValue takes and returns an Int64, as the OpenFeature Swift SDK defines it. getObjectValue returns the parsed JSON as an OpenFeature Value, a .structure for a JSON object or a .list for a JSON array:
let settings = client.getObjectValue(key: "my-json-config-key", defaultValue: .structure([:]))
let theme = settings.asStructure()?["theme"]?.asString()
For additional information regarding the OpenFeature client refer to the OpenFeature Swift SDK documentation.
Reading configs in SwiftUI
The getters are synchronous and make no network calls, so they are safe to call directly from a body. That gives you the current value, but the view will not re-render on its own when the value changes.
To have the view follow a config, re-read it whenever the provider publishes an event. OpenFeatureAPI.shared.observe() is a Combine publisher of provider events that replays the provider's current status to a new subscriber, so the view reads the current value as soon as it appears, and again after every change:
import OpenFeature
import SwiftUI
struct DarkModeToggle: View {
@State private var isOn = false
var body: some View {
Toggle("Dark mode", isOn: $isOn)
.onReceive(OpenFeatureAPI.shared.observe().receive(on: DispatchQueue.main)) { _ in
isOn = OpenFeatureAPI.shared.getClient().getBooleanValue(key: "dark-mode", defaultValue: false)
}
}
}
Update the user context
await OpenFeatureAPI.shared.setEvaluationContextAndWait(
evaluationContext: ImmutableContext(
targetingKey: "12345", // In OpenFeature, the targeting key represents the context's user ID
structure: ImmutableStructure(attributes: [
"name": .string("Example User"),
// Any arbitrary traits which can be referenced in targeting rules
"traits": .structure(["region": .string("North America")]),
])
)
)
The evaluation context maps onto the ConfigDirector user context as follows:
| OpenFeature evaluation context | ConfigDirector user context |
|---|---|
The targeting key, or otherwise an id attribute | id |
The name attribute | name |
The traits structure attribute | traits |
The boolean anonymous attribute | anonymous |
Any other attribute is ignored. Put the values your targeting rules depend on inside traits.
Awaiting
setEvaluationContextAndWait will wait until the new config values are downloaded or the connection times out. In the case of a timeout, the provider will continue to attempt to connect with the new context in the background.For additional information regarding the OpenFeature client refer to the OpenFeature Swift SDK documentation.
Events
The provider publishes its events through OpenFeatureAPI.shared.observe(). It emits configurationChanged whenever configs are updated on the dashboard or via the admin API, carrying the keys of the configs in the update:
import Combine
import OpenFeature
let subscription = OpenFeatureAPI.shared.observe().sink { event in
switch event {
case let .configurationChanged(details):
print("Configs updated: \(details?.flagsChanged ?? [])")
case .ready:
print("Config state is available")
case let .error(details):
print("ConfigDirector could not be reached: \(details?.message ?? "")")
default:
break
}
}
It emits ready when the initial config state arrives after setProviderAndWait has already returned, error when the initial connection times out, and reconciling followed by contextChanged around a context update.