Skip to main content

Swift (iOS)

This SDK supports the following platforms and versions:

  • iOS 12 and above
  • Apple TvOS 12 and above
  • Apple WatchOS 5.0 and above
Swift SDK Resources
v1.0.68
growthbook-swiftSwift Package Manager (SPM)Get help on Slack

Installation

CocoaPods

Add the following to your podfile:

source 'https://github.com/CocoaPods/Specs.git'

target 'MyApp' do
pod 'GrowthBook-IOS'
end

Then, install:

pod install

Swift Package Manager (SPM)

Add GrowthBook to your Package.swift file:

dependencies: [
.package(url: "https://github.com/growthbook/growthbook-swift.git")
]

Quick Usage

// First, create a GrowthBook instance using your unique API host and client key
var gb: GrowthBookSDK = GrowthBookBuilder(
// Your GrowthBook API host
apiHost: "https://cdn.growthbook.io",
// Your client key
clientKey: "sdk-abc123",
// User attributes for targeting
attributes: [:],
// Tracking callback for experiments
trackingCallback: { experiment, result in
// Track experiment exposures
},
// Enable/disable background sync for real-time updates
backgroundSync: false
).initializer()

// Then, add targeting attributes so you can control the release of your features
var attrs = [
"id": "12345",
"deviceId": "abc123",
"loggedIn": true,
"country": "US"
]
gb.setAttributes(attrs)

// Finally, start feature flagging!

// Boolean (On/Off) Feature Flag
if gb.isOn(feature: "feature-usage-code") {
// Feature is enabled!
}

// String/Number/JSON Feature Flag with a fallback
import Foundation // For JSON type
var value = gb.getFeatureValue(feature: "button-color", default: JSON("blue"))
print(value)

Loading Features

In order for the GrowthBook SDK to work, it needs to have feature definitions from the GrowthBook API. There are 2 ways to get this data into the SDK.

Built-in Fetching and Caching

If you pass an apiHost and clientKey into GrowthBookBuilder, it will handle the network requests, caching, retry logic, etc. for you automatically. If your feature payload is encrypted, you can also pass in an encryptionKey and it will decrypt feature flags automatically.

var gb: GrowthBookSDK = GrowthBookBuilder(
// Your GrowthBook API host
apiHost: "https://cdn.growthbook.io",
// Your client key
clientKey: "sdk-abc123",
// Encryption key if your features are encrypted
encryptionKey: "abcdef98765",
// Required user attributes for targeting (can be empty initially)
attributes: [:],
// Required tracking callback for experiments
trackingCallback: { experiment, result in
// Track experiments
},
// Enable/disable background sync with SSE
backgroundSync: false
).initializer()

If you want to refresh the features at any time (e.g. when a navigation event occurs), you can call gb.refreshCache().

Custom Integration

If you prefer to handle the network and caching logic yourself, you can instead pass in a features JSON object directly. For example, you might store features in Postgres on your back-end and send it down to your app as part of an initial bootstrap API call.

// Create JSON data for features
let featuresJSON = """
{
"feature1": {
"defaultValue": true
}
}
"""
let featuresData = featuresJSON.data(using: .utf8)!

// Initialize with features data
var gb: GrowthBookSDK = GrowthBookBuilder(
// Your feature definitions as Data object
features: featuresData,
// Required user attributes for targeting (can be empty initially)
attributes: [:],
// Required tracking callback for experiments
trackingCallback: { experiment, result in
// Track experiments
},
// Enable/disable background sync
backgroundSync: false
).initializer()

Experimentation (A/B Testing)

In order to run A/B tests on your feature flags, you need to set up a tracking callback function. This is called every time a user is put into an experiment and can be used to track the exposure event in your analytics system (Segment, Mixpanel, GA, etc.).

var gb: GrowthBookSDK = GrowthBookBuilder(
// Your GrowthBook API host
apiHost: "https://cdn.growthbook.io",
// Your client key
clientKey: "sdk-abc123",
// Required user attributes for targeting (can be empty initially)
attributes: [:],
// Called whenever someone is put into an experiment
trackingCallback: { experiment, experimentResult in
// TODO: Track in your real analytics system
print("Viewed Experiment")
print("Experiment Id: ", experiment.key)
print("Variation Id: ", experimentResult.variationId)
},
// Enable/disable background sync
backgroundSync: false
).initializer()

Background Sync

The Swift SDK supports real-time feature flag updates using Server-Sent Events (SSE). This is controlled through the backgroundSync parameter when initializing the SDK.

When backgroundSync is set to true, the SDK will establish an SSE connection to receive real-time updates whenever your feature flags change. This eliminates the need to manually refresh the cache.

When backgroundSync is set to false, you'll need to call gb.refreshCache() manually whenever you want to fetch the latest feature flags.

Refresh Handler

You can set a refresh handler to be notified when features are updated, either through background sync or manual refresh:

var gb: GrowthBookSDK = GrowthBookBuilder(
apiHost: "https://cdn.growthbook.io",
clientKey: "sdk-abc123",
attributes: [:],
trackingCallback: { experiment, result in
// Track experiments
},
// Callback when features are refreshed
refreshHandler: { success in
if success {
print("Features refreshed successfully")
} else {
print("Failed to refresh features")
}
},
backgroundSync: true
).initializer()

Reference

View detailed docs on the GitHub Repo