Skip to main content

Swift On Device Evaluation

Installation

To use the SDK in your project, you must add Statsig as a dependency.

In your Xcode, select File > Swift Packages > Add Package Dependency and enter the URL https://github.com/statsig-io/swift-on-device-evaluations-sdk.git.

You can also include it directly in your project's Package.swift. Find out the latest release version on our GitHub page.

//...
dependencies: [
// see the latest version on https://github.com/statsig-io/swift-on-device-evaluations-sdk/releases
.package(url: "https://github.com/statsig-io/swift-on-device-evaluations-sdk.git", .upToNextMinor("X.Y.Z")),
],
//...
targets: [
.target(
name: "YOUR_TARGET",
dependencies: ["StatsigOnDeviceEvaluations"]
)
],
//...

Initialize the SDK

Initialize the SDK using a Client SDK key from the "API Keys" tab on the Statsig console. When creating the key, or using an existing key, you will need to add the "Allow Download Config Specs" scope. Client keys, by default, are not able to download the project definition to do on device evaluation. You must opt in to allow your client key to access your full project definition on our cdn.

When creating a new client key, select "Allow Download Config Specs"

Add DCS Scope to Existing Key

caution

Do NOT embed a Server Secret Key in client side applications.

import StatsigOnDeviceEvaluations

// (optional) Configure the SDK if needed
let opts = StatsigOptions()
opts.environment.tier = "staging"

Statsig.shared.initialize("client-sdk-key", options: opts) { err in
if let err = err {
print("Error \(err)")
}
}

// or, create your own instance

let myStatsigInstance = Statsig()
myStatsigInstance.initialize("client-sdk-key", options: opts) { err in
if let err = err {
print("Error \(err)")
}
}


// or, with Objective C

StatsigOptions *options = [StatsigOptions new];

StatsigEnvironment *env = [StatsigEnvironment new];
env.tier = @"staging";
options.environment = env;

[[Statsig sharedInstance]
initializeWithSDKKey:@"client-sdk-key"
options:options
completion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Error %@", error);
}
}];

Working with the SDK

Checking a Feature Flag/Gate

Now that your SDK is initialized, let's check a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;) by default.

// Simple Pass/Fail check

let isPassing: Bool = Statsig.shared.checkGate("my_gate", user)


// or, the verbose FeatureGate check

let gate = Statsig.shared.getFeatureGate("my_gate", user)
print(gate.evaluationDetails.reason) // "Network" | "Cache" | "Unrecognized"
let isPassing: Bool = gate.value;


// or, using Objective C

BOOL isPassing = [[Statsig sharedInstance] checkGate:@"my_gate" forUser:user];

Reading a Dynamic Config

Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be able send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:

let config = Statsig.shared.getDynamicConfig("my_dynamic_config", user)

let name: String? = config.value["product_name"] as? String
let price: Double? = config.value["price"] as? Double

Getting an Layer/Experiment

Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but we recommend the use of layers to enable quicker iterations with parameter reuse.

// Getting values via getLayer

let layer = Statsig.shared.getLayer("my_layer", user)
let name: String? = layer.getValue(param: "product_name", fallback: "Unknown") as? String


// or, using getExperiment

let experiment = Statsig.shared.getExperiment("my_experiment", user)

let name: String? = experiment.value["product_name"] as? String
let price: Double? = experiment.value["price"] as? Double

Logging an Event

Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig - simply call the Log Event API for the event, and you can additionally provide some value and/or an object of metadata to be logged together with the event:

let event = StatsigEvent(
eventName: "add_to_cart",
value: "SKU_1234",
metadata: [
"price": "9.99",
"item_name": "CoolProduct"
]
)

Statsig.shared.logEvent(event, user)

Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.

Code Examples

Prefer seeing it in practice? Included in the open source repository are some Code Examples. View these for common use cases for the SDK. Included are both Swift and Objective C uses.

Statsig User

You need to provide a StatsigUser object to check/get your configurations. You should pass as much information as possible in order to take advantage of advanced gate and config conditions.

Most of the time, the userID field is needed in order to provide a consistent experience for a given user (see logged-out experiments to understand how to correctly run experiments for logged-out users).

Besides userID, we also have email, ip, userAgent, country, locale and appVersion as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the custom field and be able to create targeting based on them.

let user = StatsigUser(
userID: "a-user",
customIDs: ["EmployeeID": "an-employee"],
email: "user@statsig.io",
ip: "58.84.239.246",
userAgent: "Mozilla/5.0 (iPad; CPU OS 13_4_1....",
country: "NZ",
locale: "en_NZ",
appVersion: "3.2.1",
custom: ["Level": "9001"],
privateAttributes: ["SensitiveInfo": "shhh"]
)

Private Attributes

Have sensitive user PII data that should not be logged? No problem, we have a solution for it! On the StatsigUser object we also have a field called privateAttributes, which is a simple object/dictionary that you can use to set private user attributes. Any attribute set in privateAttributes will only be used for evaluation/targeting, and removed from any logs before they are sent to Statsig server.

For example, if you have feature gates that should only pass for users with emails ending in "@statsig.com", but do not want to log your users' email addresses to Statsig, you can simply add the key-value pair { email: "my_user@statsig.com" } to privateAttributes on the user and that's it!

Statsig Options

You can configure certain aspects of the SDKs behavior by passing a StatsigOptions object during initialization.

  • eventQueueMaxSize: Int, default 20

    • The maximum number of events to batch before flushing logs to the server.
  • eventQueueInternalMs: Double, default 10,000

    • How frequently to flush queued logs.
  • eventLoggingAPI: String, default https://events.statsigapi.net/v1/rgstr

    • The API where all events are sent.
  • configSpecAPI: Int, default https://api.statsigcdn.com/v1/download_config_specs/

    • The API used to fetch the latest configurations.
  • environment: StatsigEnvironment, default {}

    • An object you can use to set environment variables that apply to all of your users in the same session and will be used for targeting purposes.

Shutting Statsig Down

In order to save users' data and battery usage, as well as prevent logged events from being dropped, we keep event logs in client cache and flush periodically. Because of this, some events may not have been sent when your app shuts down.

To make sure all logged events are properly flushed or saved locally, you should tell Statsig to shutdown when your app is closing:

Statsig.shared.shutdown { err in
if let err = err {
print("An error occurred during Statsig shutdown: \(err)")
} else {
print("Statsig shutdown successfully")
}
}

Local Overrides

It is possible to override the values returned by the Statsig SDK. This can be useful in unit testing or for enabling features for local development.

To get setup with local overrides, you can use pass an instance of LocalOverrideAdapter to the SDK via the StatsigOptions object.

Note: it is possible to write your own override adapter. You can implement the OverrideAdapter protocol and pass that in instead.

let user = StatsigUser(userID: "a-user")

let overrides = LocalOverrideAdapter()

// Override a gate
overrides.setGate(user, FeatureGate.create("local_override_gate", true))

// Override a dynamic config (Similar for Layer and Experiment)
overrides.setDynamicConfig(user, DynamicConfig.create("local_override_dynamic_config", ["foo": "bar"]))

let opts = StatsigOptions()
opts.overrideAdapter = overrides

Statsig.shared.initialize(YOUR_SDK_KEY, options: opts) { _ in
let gate = Statsig.shared.getFeatureGate("local_override_gate", user)
print("Result: \(gate.value) (\(gate.evaluationDetails.reason))")
}

FAQ

How do I run experiments for logged out users?

See the guide on device level experiments