
## Set up the SDK

{% steps %}
{% step title="Install the SDK" %}
To use the SDK in your project, add Statsig as a dependency.

{% tabs %}
{% tab title="Swift Package Manager" %}
In your Xcode, select File > Swift Packages > Add Package Dependency
and enter the URL https://github.com/statsig-io/statsig-kit.git.

You can also include it directly in your project's Package.swift. Find the latest release version on the [GitHub page](https://github.com/statsig-io/statsig-kit/releases).

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

{% /tab %}

{% tab title="Cocoapods" %}
If you use CocoaPods, the pod name is 'Statsig'. Include the following line in your Podfile:

```ruby
use_frameworks!
target 'TargetName' do
  //...
  pod 'Statsig', '~> X.Y.Z'
end
```

Find the latest versions by searching [cocoapods.org](https://cocoapods.org/) or on [Github](https://github.com/statsig-io/statsig-kit/releases).
{% /tab %}
{% /tabs %}
{% /step %}

{% step title="Initialize the SDK" %}
Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application.

Along with the key, pass in a [User Object](#statsig-user) with the attributes you want to target later in a gate or experiment.

{% codetabs %}

```swift Swift
Statsig.initialize(
    sdkKey: "my_client_sdk_key",
    user: StatsigUser(userID: "my_user_id"),
    options: StatsigOptions(environment: StatsigEnvironment(tier: .Staging)))
{ error in

  // Statsig has finished fetching the latest feature gate and experiment values for your user.
  // If you need the most recent values, you can get them now.

  // You can also check error.message and error.code for any debugging information.

}
```

```objective-c Objective C
StatsigUser *user = [[StatsigUser alloc] initWithUserID:@"my_user_id"];
[Statsig initializeWithSDKKey:@"my_client_sdk_key" user:user completion:^(StatsigClientError * error) {
  // Statsig has finished fetching the latest feature gate and experiment values for your user.
  // If you need the most recent values, you can get them now.

  // You can also check error.message and error.code for any debugging information.
}];
```

{% /codetabs %}

The SDK calls the completion block after the network request to fetch the latest feature gate and experiment values for your user.
If you request any value before the SDK calls the completion block, you may get the cached value from the previous session or the default value. Wait for the completion block before requesting the latest value.
{% /step %}
{% /steps %}

## Use the SDK

### Checking a Feature Flag/Gate

Now that your SDK is initialized, check a [**Feature Gate**](/feature-flags/overview). Feature Gates 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.

{% codetabs %}

```swift Swift
if Statsig.checkGate("new_homepage_design") {
  // Gate is on, show new home page
} else {
  // Gate is off, show old home page
}
```

```objective-c Objective C
if ([Statsig checkGateForName:@"new_homepage_design"]) {
  // Gate is on, show new home page
} else {
  // Gate is off, show old home page
}
```

{% /codetabs %}

### Reading a Dynamic Config

Feature Gates work well for simple on/off switches with optional advanced user targeting. To send different values (strings, numbers, and similar types) to your clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates but returns a full JSON object you can configure on the server and fetch typed parameters from. For example:

{% codetabs %}

```swift Swift
let config = Statsig.getConfig("awesome_product_details")

// The 2nd parameter is the default value to be used in case the given parameter name does not exist on
// the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the
// value has not been cached on the client.
let itemName = config.getValue(forKey: "product_name", defaultValue: "Awesome Product v1")
let price = config.getValue(forKey: "price", defaultValue: 10.0)
let shouldDiscount = config.getValue(forKey: "discount", defaultValue: false)
```

```objective-c Objective C
DynamicConfig *config = [Statsig getConfigForName:@"awesome_product_details"];

// The 2nd parameter is the default value to be used in case the given parameter name does not exist on
// the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the
// value has not been cached on the client.
NSString *itemName = [config.getStringForKey:@"product_name" defaultValue:@"Awesome Product v1"];
double price = [config getDoubleForKey:@"price" defaultValue:10.0];
BOOL shouldDiscount = [config getBoolForKey:@"discount" defaultValue:false];
```

{% /codetabs %}

### Getting a Layer/Experiment

Use **Layers/Experiments** to run A/B/n experiments. Statsig offers two APIs, but recommends [layers](/experiments/layers-overview) to enable quicker iterations with parameter reuse.

{% codetabs %}

```swift Swift
// Values via getLayer

let layer = Statsig.getLayer("user_promo_experiments")
let promoTitle = layer.getValue(forKey: "title", defaultValue: "Welcome to Statsig!")
let discount = layer.getValue(forKey: "discount", defaultValue: 0.1)

// or, via getExperiment

let titleExperiment = Statsig.getExperiment("new_user_promo_title")
let priceExperiment = Statsig.getExperiment("new_user_promo_price")

let promoTitle = titleExperiment.getValue(forKey: "title", defaultValue: "Welcome to Statsig")
let discount = priceExperiment.getValue(forKey: "discount", defaultValue: 0.1)

...

let price = msrp * (1 - discount);
```

```objective-c Objective C
DynamicConfig *expConfig = [Statsig getExperimentForName:@"new_user_promo"];

NSString *promoTitle = [expConfig.getStringForKey:@"title" defaultValue:@"Welcome to Statsig! Use discount code WELCOME10OFF for 10% off your first purchase!"];
double discount = [expConfig getDoubleForKey:@"discount" defaultValue:0.1];

double price = msrp * (1 - discount);
```

{% /codetabs %}

### Logging an Event

After you set up a Feature Gate or an Experiment, you can track custom events to measure how your new features or experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and/or a metadata object to log together with the event:

{% codetabs %}

```swift Swift
Statsig.logEvent(withName: "purchase", value: 2.99, metadata: ["item_name": "remove_ads"])
```

```objective-c Objective C
[Statsig logEvent:@"purchase" doubleValue:2.99 metadata:@{ @"item_name" : @"remove_ads" }];
```

{% /codetabs %}

## Parameter Stores

Parameter Stores hold a set of parameters for your mobile app. These parameters can be remapped dynamically from a static value to a Statsig entity (Feature Gates, Experiments, and Layers), so you can decouple your code from the configuration in Statsig. Go to [Parameter Stores](/client/concepts/parameter-stores) to learn more.

## Statsig User

Provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions.

The `userID` field is usually required to provide a consistent experience for a given user. (Refer to [logged-out experiments](/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users.)

Besides `userID`, the `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion` fields are also available as top-level fields on StatsigUser. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them.

After the user logs in or their attributes change, call `updateUserWithResult` with the updated `userID` and/or any other updated user attributes.

{% codetabs %}

```swift Swift
let user = StatsigUser(
  userID: "a-user-id",
  email: "user@example.com",
  ip: "192.168.1.1",
  userAgent: "Mozilla/5.0",
  country: "US",
  locale: "en_US",
  appVersion: "1.0.0",
  custom: [
    "plan": "premium",
    "age": 25
  ],
  customIDs: [
    "stableID": "stable-id-123"
  ],
  privateAttributes: [
    "email": "private@example.com"
  ]
)
```

```objective-c Objective C
StatsigUser *user = [[StatsigUser alloc] initWithUserID:@"a-user-id"];
user.email = @"user@example.com";
user.ip = @"192.168.1.1";
user.userAgent = @"Mozilla/5.0";
user.country = @"US";
user.locale = @"en_US";
user.appVersion = @"1.0.0";
user.custom = @{ @"plan": @"premium", @"age": @25 };
user.customIDs = @{ @"stableID": @"stable-id-123" };
user.privateAttributes = @{ @"email": @"private@example.com" };
```

{% /codetabs %}

## Statsig Options

{% parameter name="initTimeout" type="Double" %}
Determines how long the Statsig client waits for the initial network request to respond before calling the completion block. The Statsig client returns either cached values (if any) or default values if checkGate/getConfig/getExperiment is called before the initial network request completes.

If you always want to wait for the latest values fetched from Statsig server, set this to 0 to avoid timing out the network request.
{% /parameter %}

{% parameter name="disableCurrentVCLogging" type="Bool" %}
By default, any custom event your application logs with `Statsig.logEvent()` includes the current root View Controller. This allows Statsig to generate user journey funnels for your users. Set this parameter to `true` to disable this behavior.
{% /parameter %}

{% parameter name="printHandler" type="((String) -> Void)?" %}
A handler for log messages from the SDK. If not provided, the SDK prints logs to the console.

The handler receives the message string that would otherwise be printed to the console.

Useful for redirecting logs to your own logging system, suppressing unnecessary console output, or debugging issues with the SDK.
{% /parameter %}

{% parameter name="environment" type="StatsigEnvironment" %}
StatsigEnvironment is a class for setting environment variables that apply to all of your users in the same session. Statsig uses these variables for targeting purposes.

For example, passing in a value of `StatsigEnvironment(tier: .Staging)` allows your users to pass any condition that passes for the staging environment tier, and fail any condition that only passes for other environment tiers.
{% /parameter %}

{% parameter name="evaluationCallback" type="EvaluationCallbackData" %}
EvaluationCallback provides a callback when an evaluation occurs against one of your configurations (gate, dynamic config, experiment, layer, and parameter stores). This is useful when you want to trigger specific actions or log evaluations based on the results received from Statsig.

To use the EvaluationCallback, provide a callback function during SDK initialization through StatsigOptions. The SDK invokes the callback every time an evaluation occurs for feature gates, dynamic configs, experiments, layers, or parameter stores.

The EvaluationCallbackData enum defines the different types of data that the evaluationCallback returns when the Statsig iOS SDK evaluates feature gates, dynamic configs, experiments, layers, or parameter stores.

Here is the structure of the enum:

```swift
   public enum EvaluationCallbackData {
      case gate (FeatureGate)
      case config (DynamicConfig)
      case experiment (DynamicConfig)
      case layer (Layer)
      case parameterStore (ParameterStore)
   }
```

Here's an example of how to set up an evaluation callback:

```swift
    func callback(data: StatsigOptions.EvaluationCallbackData) {
       switch data {
       case .gate(let gate):
          // Handle gate evaluation
       case .config(let config):
          // Handle dynamic config evaluation
       case .experiment(let experiment):
          // Handle experiment evaluation
       case .layer(let layer):
          // Handle layer evaluation
       case .parameterStore(let paramStore):
          // Handle parameter store evaluation
       }
    }

    let opts = StatsigOptions(evaluationCallback: callback)
    Statsig.initialize(sdkKey: "client-key", options: opts)
```

{% /parameter %}

{% parameter name="storageProvider" type="StorageProvider" %}
Lets you implement a custom caching strategy by passing an object that conforms to the `StorageProvider` protocol.

Default cache key: `com.statsig.cache`

```swift
   @objc public protocol StorageProvider {
      @objc func read(_ key: String) -> Data?
      @objc func write(_ value: Data, _ key: String)
      @objc func remove(_ key: String)
   }
```

{% /parameter %}

{% parameter name="overrideStableID" type="String" %}
Overrides the auto generated StableID that is set for the device.
{% /parameter %}

{% parameter name="enableCacheByFile" type="Bool" %}
Use file caching instead of UserDefaults. Useful if you run into size limits with UserDefaults (ie tvOS).
{% /parameter %}

{% parameter name="eventLoggingEnabled" type="Bool" %}
Controls whether the SDK sends events over the network. Useful when user consent is needed before sending events. The iOS SDK stores up to 1MB of unsent request payloads.
{% /parameter %}

{% parameter name="initializeValues" type="[String: Any]" %}
Provide a Dictionary representing the "initialize response" required to synchronously initialize the SDK.
Obtain this value from a Statsig server SDK and use it to [Bootstrap](/client/concepts/initialize/#2-bootstrap-initialization) the SDK when initializing.
{% /parameter %}

{% parameter name="disableDiagnostics" type="Bool" %}
Prevent the SDK from sending useful debug information to Statsig.
{% /parameter %}

{% parameter name="disableHashing" type="Bool" %}
When disabled, the SDK doesn't hash gate/config/experiment names, and they remain readable as plain text.

{% callout type="info" %}
This requires special authorization from Statsig. Reach out to the support team, your sales contact, or through the [Slack community](https://statsig.com/slack) if you want this enabled.
{% /callout %}
{% /parameter %}

{% parameter name="shutdownOnBackground" type="Bool" %}
The SDK automatically shuts down when an app enters the background.
If you need to use the SDK while your app is in the background, set this to `false`.
{% /parameter %}

{% parameter name="initializationURL" type="URL" %}
Override the URL used to initialize the SDK. Learn more at /custom_proxy

```swift
   StatsigOptions(initializationURL: URL(string: "https://example.com/setup"))
```

{% /parameter %}

{% parameter name="eventLoggingURL" type="URL" %}
Override the URL used to log events. Learn more at /custom_proxy

```swift
   StatsigOptions(eventLoggingURL: URL(string: "https://example.com/info"))
```

{% /parameter %}

## StableID

Each client SDK has the concept of stableID: a device-level identifier generated the first time the SDK is initialized and stored locally for all future sessions. Unless storage is wiped (or the app is deleted), the stableID doesn't change.
This allows Statsig to run device-level experiments and experiments when other user-identifiable information is unavailable (logged-out users).

{% codetabs %}

```swift Swift
let options = StatsigOptions(overrideStableID: "my_stable_id")
Statsig.initialize(sdkKey: "client-xyz", options: options)
```

```objective-c Objective C
StatsigOptions *options = [[StatsigOptions alloc] init];
options.overrideStableID = @"my_stable_id";
[Statsig initializeWithSDKKey:@"client-xyz" user:nil options:options completion:nil];
```

{% /codetabs %}

## Manual Exposures

{% callout type="warning" %}
Manual logging is error-prone and can often introduce issues like uneven exposures, which compromise experiment results.
{% /callout %}

You can query your gates/experiments without triggering an exposure and manually log the exposures later.

{% tabs %}
{% tab title="Feature Gates" %}
{% codetabs %}

```swift Swift
// Swift - Check without logging exposure
let result = Statsig.checkGateWithExposureLoggingDisabled("a_gate_name")
// ...
// Later, when ready to log the exposure
Statsig.manuallyLogGateExposure("a_gate_name")
```

```objc Objective-C
// Objective C - Check without logging exposure
bool result = [Statsig checkGateWithExposureLoggingDisabled:@"a_gate_name"];
// ...
// Later, when ready to log the exposure
[Statsig manuallyLogGateExposure:@"a_gate_name"];
```

{% /codetabs %}
{% /tab %}

{% tab title="Dynamic Configs" %}
{% codetabs %}

```swift Swift
// Swift - Get config without logging exposure
let config = Statsig.getConfigWithExposureLoggingDisabled("a_config_name")
// ...
// Later, when ready to log the exposure
Statsig.manuallyLogConfigExposure("a_config_name")
```

```objc Objective-C
// Objective C - Get config without logging exposure
DynamicConfig *config = [Statsig getConfigWithExposureLoggingDisabled:@"a_config_name"];
// ...
// Later, when ready to log the exposure
[Statsig manuallyLogConfigExposure:@"a_config_name"];
```

{% /codetabs %}
{% /tab %}

{% tab title="Experiments" %}
{% codetabs %}

```swift Swift
// Swift - Get experiment without logging exposure
let experiment = Statsig.getExperimentWithExposureLoggingDisabled("an_experiment_name")
// ...
// Later, when ready to log the exposure
Statsig.manuallyLogExperimentExposure("an_experiment_name")
```

```objc Objective-C
// Objective C - Get experiment without logging exposure
DynamicConfig *experiment = [Statsig getExperimentWithExposureLoggingDisabled:@"an_experiment_name"];
// ...
// Later, when ready to log the exposure
[Statsig manuallyLogExperimentExposure:@"an_experiment_name"];
```

{% /codetabs %}
{% /tab %}

{% tab title="Layers" %}
{% codetabs %}

```swift Swift
// Swift - Get layer without logging exposure
let layer = Statsig.getLayerWithExposureLoggingDisabled("a_layer_name")
let result = layer.getValue(forKey: "a_parameter_name", defaultValue: "fallback")
// ...
// Later, when ready to log the exposure
Statsig.manuallyLogLayerParameterExposure("a_layer_name", "a_parameter_name")
```

```objc Objective-C
// Objective C - Get layer without logging exposure
Layer *layer = [Statsig getLayerWithExposureLoggingDisabled:@"a_layer_name"];
NSString *result = [layer getStringForKey:@"a_parameter_name" defaultValue:@"fallback"];
// ...
// Later, when ready to log the exposure
[Statsig manuallyLogLayerParameterExposure:@"a_layer_name" parameterName:@"a_parameter_name"];
```

{% /codetabs %}
{% /tab %}
{% /tabs %}

## Local Overrides

To locally override gates/configs/experiments/layers for testing, use the local override methods. Unless you call the remove method, these overrides persist session-to-session on the client's device. These overrides apply locally only and don't affect definitions in the console or elsewhere.

## Shutting Statsig Down

To save users' data and battery usage and prevent logged events from being dropped, the SDK keeps event logs in client cache and flushes them periodically. Because of this, some events may not have been sent when your app shuts down.

To ensure all logged events are flushed or saved locally, call shutdown when your app is closing.

{% codetabs %}

```swift Swift
Statsig.shutdown()
```

```objective-c Objective C
[Statsig shutdown];
```

{% /codetabs %}

## Using multiple instances of the SDK

The examples above use the SDK's singleton. Statsig also supports creating multiple instances of the SDK. The `Statsig` singleton wraps a single instance of the SDK (typically called a `StatsigClient`) that you can instantiate directly.

{% callout type="note" %}
Use a different SDK key for each SDK instance. Various functionality of the Statsig client is keyed on the SDK key being used. Using the same key causes collisions.
{% /callout %}

All top-level static methods from the singleton carry over as instance methods. To create an instance of the Statsig SDK:

{% codetabs %}

```swift Swift
let client = StatsigClient(
    sdkKey: "client-xyz",
    user: StatsigUser(userID: "user-1"),
    options: StatsigOptions(environment: StatsigEnvironment(tier: .Production))
) { error in
  // ready
}

let gateOn = client.checkGate("some_gate")
```

```objective-c Objective C
StatsigOptions *options = [[StatsigOptions alloc] initWithEnvironment:[[StatsigEnvironment alloc] initWithTier:StatsigEnvironmentTierProduction]];
StatsigUser *user = [[StatsigUser alloc] initWithUserID:@"user-1"];
StatsigClient *client = [[StatsigClient alloc] initWithSdkKey:@"client-xyz" user:user options:options completion:^(StatsigClientError * error) {
  // ready
}];

BOOL gateOn = [client checkGate:@"some_gate"];
```

{% /codetabs %}

{% callout type="warning" %}
Use a unique SDK key per instance to avoid collisions.
{% /callout %}

## Initialize Response

The SDK provides a method to access the raw values used internally for gate, config, and layer values. This is useful for debugging or for advanced use cases where you need to access the underlying data. For example, you can use these values to bootstrap another SDK, such as the JavaScript SDK when you open an in-app browser.

The `getInitializeResponseJson` method returns an `ExternalInitializeResponse` object that contains:

1. A JSON string representation of the initialize response values
2. Evaluation details that provide metadata about how the values were obtained (network, cache, etc.)

{% codetabs %}

```swift Swift
let response = Statsig.getInitializeResponseJson()
if let values = response.values {
    print(values)
}
let details = response.evaluationDetails
```

```objective-c Objective C
ExternalInitializeResponse *response = [Statsig getInitializeResponseJson];
NSString *values = response.values;
if (values) {
    NSLog(@"%@", values);
}
EvaluationDetails *details = response.evaluationDetails;
```

{% /codetabs %}

## Listening for changes

In v1.14.0+, you can listen for SDK changes using `StatsigListening`.

{% codetabs %}

```swift Swift
class MyViewController: UIViewController, StatsigListening {

    override func viewDidLoad() {
        super.viewDidLoad()

        if Statsig.isInitialized() {
            render()
        } else {
            Statsig.addListener(self)
            renderLoading()
        }
    }

    private func render() {
        let showNewUI = Statsig.checkGate("new_ui_enabled")
        if showNewUI {
            // Render the new UI
        } else {
            // Render the old UI
        }
    }

    private func renderLoading() { /* loading UI */ }
    private func renderError(error: StatsigClientError) { /* error UI */ }

    // StatsigListening
    func onInitializedWithResult(_ error: StatsigClientError?) {
        if let error = error {
            renderError(error)
            return
        }
        render()
    }

    func onUserUpdatedWithResult(_ error: StatsigClientError?) { /* optional rerender */ }
}
```

{% /codetabs %}
