SDKs
iOS and Swift SDK
On this page
Install
Swift Package Manager (in Xcode: File → Add Package Dependencies…, then enter the repository URL):
.package(url: "https://github.com/motazalmaroai/nanoflags-swift", from: "0.1.0")
// target dependency:
.product(name: "NanoFlags", package: "nanoflags-swift")0.1.0.- Swift 5.9 or newer (Xcode 15+):
async/await,Sendabletypes, AsyncSequences and closure listeners. - Products:
NanoFlags(the client and SwiftUI helpers) andNanoFlagsEngine(the evaluation engine alone). - The engine is a port of the NanoFlags engine, tested against the shared parity fixtures (21,998 cases) on Linux, macOS and the iOS simulator, with results identical to every other NanoFlags SDK.
- Apache-2.0.
Client keys
A mobile app ships its key to every device, so the SDK accepts browser/client keys (nf_pub_…) only. They receive the client view: client-exposed flags and only the segments those flags use. Server keys (nf_srv_…) are refused without a single request.
Quickstart
import NanoFlags
let flags = NanoFlags.start(key: "nf_pub_…", options: .init(
context: NanoFlagsContext(key: NanoFlags.anonymousKey, attributes: ["plan": "free", "appVersion": "2.4.0"])
))
// Synchronous, local, never throws: your default until a configuration is loaded.
if flags.boolVariation(key: "new-checkout", default: false) { showNewCheckout() }
let accent = flags.stringVariation(key: "accent", default: "blue")
let limit = flags.numberVariation(key: "upload-limit", default: 10)
let theme = flags.jsonVariation(key: "theme", default: ["dark": false])
// Why? (matched rule, rollout bucket, revision, a step-by-step trace)
let detail = flags.variationDetail(key: "new-checkout", default: false)
print(detail.reason, detail.ruleId ?? "-", detail.revision)
// Signed in: change the context. Local and synchronous, no network round trip.
flags.identify(context: ["key": "user-42", "plan": "pro"])
// Optional: wait for the first configuration (offline starts use the persisted one).
await flags.ready(timeout: 3)Typed variations: boolVariation, stringVariation, numberVariation, intVariation (whole numbers only) and jsonVariation, plus variationDetail and allFlags. Without a configuration, for a missing flag or a value of another type you get your default.
Listening for changes
// Closures (keep the subscription to cancel it later).
let sub = flags.onChange { change in print(change.revision ?? 0, change.changedFlags, change.transport) }
flags.onChange(key: "new-checkout", default: false) { on in print("new-checkout is now", on) }
// AsyncSequences
for await change in flags.changes { print(change.changedFlags) }
for await on in flags.values(key: "new-checkout", default: false) { update(on) }
flags.onStatusChange { print($0) } // .notReady / .ready / .stale
flags.onError { print($0) } // a rejected key, a bundle that failed verification, the network, …changedFlags lists the flags whose value for the current context changed.
SwiftUI
struct CheckoutButton: View {
@FeatureFlag("new-checkout", default: false) var newCheckout // follows NanoFlags.shared
var body: some View { Button(newCheckout ? "Pay now" : "Checkout") { … } }
}
// ObservableObject (iOS 14+)
@StateObject var flags = NanoFlagsObservable.shared // or NanoFlagsObservable(client: client)
Text(flags.string("accent", default: "blue"))
.onFlagChange("accent", default: "blue") { print("accent →", $0) }
// Observation (iOS 17+)
@State var model = NanoFlagsModel(client: NanoFlags.shared!)
if model.bool("new-checkout", default: false) { NewCheckout() }Views re-render when the configuration, the context (identify) or the status changes.
Options
NanoFlagsOptions(
baseURL: NanoFlags.officialEdgeURL, // your own edge for self-hosting
context: .empty,
service: nil, // default: the bundle identifier
transport: .automatic, // .serverSentEvents, .polling
pollInterval: 30, livePollInterval: 300, lowDataPollInterval: 900,
respectLowDataMode: true, pauseInBackground: true,
verify: .automatic, // .enabled(VerifyOptions(publicKeys:fetchKeys:require:)), .disabled
storage: .applicationSupport, // .userDefaults(suiteName:), .directory(url), .custom(...), .none
bootstrap: nil, // bundle JSON shipped with the app
events: EventsOptions(), // .disabled
requestTimeout: 10, callbackQueue: nil, userAgentSuffix: nil)Callbacks run on the SDK's thread unless you set callbackQueue (for example .main).
Live updates and lifecycle
- Live updates over
URLSessionWebSocketTask(/v1/live), with SSE and ETag polling as fallbacks, jittered backoff, socket rotation and a safety poll. Close code4004(environment deleted) stops reconnecting and keeps the last configuration asstale. - Background and foreground: in the background the live connection is closed and polling stops; on return to the foreground the SDK reconnects and catches up.
pause()andresume()do the same manually. - Low Data Mode: when
NWPath.isConstrained, no socket or stream is kept, telemetry is paused and the configuration is polled every 15 minutes. - Offline-first: the last verified bundle is stored in Application Support (excluded from backups) and verified again at launch, so the app starts with the right flags without a network.
bootstrapcovers the very first start. - Every request sends
User-Agent: nanoflags-swift/0.1.0 (<OS> <version>).
Signature verification
Bundles are verified by key id with Ed25519 (CryptoKit on Apple platforms, swift-crypto on Linux) against the production keys embedded in the package. An unknown key id loads GET /v1/keys (at most once a minute). Unsigned and tampered bundles are refused by default, and so are bundles for a newer engine; the configuration in use stays. See Security.
OpenFeature provider
The provider for the OpenFeature Swift SDK (0.7.x) is a separate package, nanoflags-openfeature-swift, because OpenFeature requires iOS 15 / tvOS 15 / watchOS 8 and Combine (and Swift 6.1, Xcode 16.3+), while the core supports iOS 14 and Linux.
// Package.swift
.package(url: "https://github.com/motazalmaroai/nanoflags-openfeature-swift", from: "0.1.0")
.product(name: "NanoFlagsOpenFeature", package: "nanoflags-openfeature-swift")
// App
import NanoFlagsOpenFeature
import OpenFeature
let provider = NanoFlagsProvider(client: NanoFlags.start(key: "nf_pub_…"))
await OpenFeatureAPI.shared.setProviderAndWait(provider: provider, initialContext: ImmutableContext(targetingKey: "user-42"))
let on = OpenFeatureAPI.shared.getClient().getBooleanValue(key: "new-checkout", defaultValue: false)Mapping (as in the other NanoFlags providers): targeting key → key; off → DISABLED, default → DEFAULT, fixed rule → TARGETING_MATCH, rollout → SPLIT; the variant is the rule id; events READY, STALE, ERROR, CONFIGURATION_CHANGED and CONTEXT_CHANGED.
Telemetry
A service report and sampled evaluation events (sdk: "swift/0.1.0") with attribute names and types only, never values. Pass events: .disabled to opt out.
Platform notes
| Linux | macOS | iOS simulator / device | |
|---|---|---|---|
| Engine parity (21,998 cases), signature verification | ✓ swift-crypto | ✓ CryptoKit | ✓ CryptoKit |
| Live updates | SSE and polling | WebSocket | WebSocket |
| Lifecycle and SwiftUI helpers | — | ✓ AppKit | ✓ UIKit |
| OpenFeature provider | — | ✓ | ✓ |
- Linux: swift-corelibs-foundation's URLSession is usually built without WebSocket support. The SDK detects this once and uses SSE and polling, so updates take seconds instead of a fraction of a second.
- Strings: Swift strings cannot hold lone UTF-16 surrogates; the engine's JSON parser turns them into U+FFFD. Real configurations never contain them.
- Numbers are IEEE-754 doubles, as in JavaScript;
intVariationaccepts whole numbers only.