LiftCanary

SDKs

iOS (Swift)

Swift Package for iOS, macOS, tvOS and watchOS, with SwiftUI property wrappers and offline storage.

LiftCanary is a Swift package for iOS, iPadOS, macOS, tvOS, watchOS and visionOS apps. Flags are decided on the device from a datafile that is refreshed in the background, so a decision is synchronous, takes microseconds and is safe in a SwiftUI body. A user gets the same variation as on your website, in your Android app and on your servers.

Install#

Swift Package Manager: in Xcode, choose File → Add Package Dependencies… and enter https://github.com/liftcanary/liftcanary-swift (from 0.1.0). In a Package.swift:

Package.swift
.package(url: "https://github.com/liftcanary/liftcanary-swift", from: "0.1.0")
// and in your target's dependencies:
.product(name: "LiftCanary", package: "liftcanary-swift")

CocoaPods: add the pod to your Podfile and run pod install.

Podfile
pod "LiftCanary", "~> 0.1"

iOS 13, macOS 10.15, tvOS 13 or watchOS 6 and later, Swift 5.9 or newer (clean under Swift 6 strict concurrency). Foundation only, no other dependencies.

Set up the client#

Swift
import LiftCanary

let liftcanary = LiftCanary.Client(sdkKey: "pk_live_...") // once, at app start
await liftcanary.ready()                                   // at most 3 s

Create one client and keep it for the app's lifetime; it starts downloading the datafile and sending events right away. ready(timeout:) waits for the first datafile, and if the download fails or is slower, uses the one saved by the last launch. Until a datafile is loaded every flag is off with reason .notReady. In UIKit, liftcanary.ready(timeout: 2) { ok in … } calls its completion handler on the main queue.

Flags, variables and events#

Swift
let user = liftcanary.createUser(id: LiftCanary.anonymousId(), attributes: [
    "plan": "pro", "country": "TR", "platform": "ios", "app_version": "2.4.0",
])

if user.isEnabled("new_checkout") { showNewCheckout() }
let buttonText = user.variable("new_checkout", "button_text", default: "Buy now")
user.track("purchase", value: 49.90, properties: ["currency": "TRY"])
isEnabled(_:)
Bool
Whether the flag is on. False until the datafile is loaded.
variable(_:_:default:)
T
A typed variable (String, Bool, Double, Int, [String: Any], [Any], JSONValue, or any Decodable with as:), or the default when the flag or variable is missing, null or of another kind.
decide(_:sendExposure:)
Decision
flagKey, enabled, variationKey, ruleKey, inExperiment, reason, variables, revision. Logs an experiment exposure unless sendExposure: false; then call logExposure(_:) when it's shown.
decideAll()
[String: Decision]
Every flag in the datafile.
track(_:value:properties:)
Void
A goal event. value must be finite.

A UserContext is immutable and thread-safe, and decisions never wait for I/O. Attributes, variables and properties are LiftCanary.JSONValues written as literals; targeting is type-strict, so "10" never equals 10. Network and data errors are logged, never thrown into the app.

SwiftUI#

Put the client and the user in the environment once. Views below read flags with property wrappers and re-render when a newer datafile arrives, so a kill switch reaches open screens without a restart.

Swift
// Once, near the root of your view tree:
ContentView().liftCanary(liftcanary, user: user)

struct CheckoutScreen: View {
    @LiftCanaryFlag("new_checkout") var newCheckout                                      // Bool; $newCheckout is the Decision
    @LiftCanaryVariable("new_checkout", "button_text", default: "Buy now") var buttonText // String
    @Environment(\.liftCanary) var liftCanary

    var body: some View {
        VStack {
            if newCheckout { OnePageCheckout() } else { ClassicCheckout() }
            Button(buttonText) { liftCanary?.track("purchase", value: 49.90) }
        }
    }
}
.liftCanary(client, user:)
modifier
Provides the client and the user to every view below.
@LiftCanaryFlag(flagKey)
Bool
Whether the flag is on; $name is the full Decision. Off outside .liftCanary(…) and before the datafile is loaded.
@LiftCanaryVariable(flagKey, name, default:)
Value
A typed variable, or the default. $name is the flag's Decision.
@Environment(\.liftCanary)
LiftCanaryContext?
client, user, revision, decision(_:) (logs no exposure) and track; nil outside the modifier.
LiftCanaryObservable(client:userId:)
ObservableObject
Keep the user in a @StateObject instead: set its user on sign-in and views re-render. .liftCanary(flags) shares it with the property wrappers.

The property wrappers and LiftCanaryObservable log an experiment exposure once per user, flag, rule and variation, right after the view update, never as a side effect of body.

Anonymous users and signing in#

LiftCanary.anonymousId() is a random UUID created on first use and kept in UserDefaults under liftcanary:anonymous_id, so it stays the same across launches. Use it as the user id until the person signs in. Then create the user with your id and pass the anonymous id as anonymousId: the SDK sends one identify event per pair, so results count the visits before and after sign-in as one person.

Swift
let user = liftcanary.createUser(id: account.id, attributes: ["plan": "pro"], anonymousId: LiftCanary.anonymousId())

Switching ids can change the variation; to keep the one they had while signed out, also pass the anonymous id as bucketingId. After sign-out, LiftCanary.resetAnonymousId() starts a new id. See From landing page to app.

Offline and the app lifecycle#

  • The datafile is checked every 60 seconds and when the app returns to the foreground (with If-None-Match, so no change costs a 304). Only a newer revision is applied.
  • Each download is saved in Application Support (Caches on tvOS). The next launch still tries the network first, so a kill switch always wins; the saved datafile is used only when the download fails or ready() times out. An app opened offline decides with its last configuration.
  • Events are sent in batches of 20 every 5 seconds, and when the app goes to the background, inside a background task so the request can finish. Failed batches are retried with backoff up to 60 s.
  • Unsent events (the newest 200) are saved within a second and sent on the next launch. client.close() stops the client and saves what couldn't be sent.
  • On macOS, becoming active refreshes the datafile, resigning active sends events, and quitting saves the unsent ones.

On the very first launch there is nothing saved, so without network flags are off until a datafile arrives. To decide immediately even then, ship a datafile in the app bundle and pass it as datafile; newer revisions replace it as they download.

Swift
let bundled = Bundle.main.url(forResource: "liftcanary-datafile", withExtension: "json")
    .flatMap { try? Data(contentsOf: $0) }
    .flatMap { try? LiftCanary.Datafile(data: $0) }
let liftcanary = LiftCanary.Client(sdkKey: "pk_live_...", options: .init(datafile: bundled))

Options#

Pass them as LiftCanary.Client(sdkKey: …, options: .init(…)), in the order below (Swift requires it), like the bundled datafile above.

datafile
Datafile?
A datafile to start from (bundled with the app), so the first decisions need no download.
cdnURL
https://cdn.liftcanary.com
Where datafiles are served: {cdnURL}/datafiles/{sdkKey}.json. Your own domain or a self-hosted LiftCanary.
eventsURL
https://events.liftcanary.com
The collector: {eventsURL}/v1/batch.
pollingInterval
60
Seconds between datafile checks; 0 turns polling off.
eventBatchSize
20
Events per request.
eventFlushInterval
5
Seconds between sends; 0 sends only full batches and on flush().
eventMaxQueueSize
1000
Events held in memory before the oldest are dropped (counted in client.events.dropped).
cacheDatafile
true
Keep the last datafile in storage and use it when a download fails or ready() times out.
storage
FileStorage()
Where the datafile and unsent events are kept. nil keeps everything in memory.
refreshOnForeground
true
Download the datafile when the app returns to the foreground.
flushOnBackground
true
Send queued events when the app goes to the background.
transport
URLSessionTransport()
The HTTP layer; your own HTTPTransport for a proxy or tests.
logger
OSLogLogger()
Warnings and errors to the unified log. PrintLogger and SilentLogger are the alternatives.