Skip to main content
Version: Config V2

Swift (iOS) SDK Reference

Star on GitHub Build Status CocoaPods Supported Platforms Coverage Status Quality Gate Status

ConfigCat Swift SDK on GitHub

Getting Started

1. Add the ConfigCat SDK to your project

Podfile
target '<YOUR TARGET>' do
pod 'ConfigCat'
end

Then, run the following command to install your dependencies:

pod install

2. Import the ConfigCat SDK

import ConfigCat

3. Create the ConfigCat client with your SDK Key

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#")

4. Get your setting value

client.getValue(for: "isMyAwesomeFeatureEnabled", defaultValue: false) { isMyAwesomeFeatureEnabled in
if isMyAwesomeFeatureEnabled {
doTheNewThing()
} else {
doTheOldThing()
}
}

// Or with async/await
let isMyAwesomeFeatureEnabled = await client.getValue(for: "isMyAwesomeFeatureEnabled", defaultValue: false)
if isMyAwesomeFeatureEnabled {
doTheNewThing()
} else {
doTheOldThing()
}

5. Close ConfigCat client​

You can safely shut down all clients at once or individually and release all associated resources on application exit.

ConfigCatClient.closeAll() // closes all clients

client.close() // closes the specific client

Supported platform versions

The following device platform versions are supported:

PlatformVersion
iOS>= 12.0
watchOS>= 4.0
tvOS>= 12.0
macOS>= 10.13
visionOS>= 1.0

Creating the ConfigCat Client

ConfigCat Client is responsible for:

  • managing the communication between your application and ConfigCat servers.
  • caching your setting values and feature flags.
  • serving values quickly in a failsafe way.

ConfigCatClient.get(sdkKey: <sdkKey>) returns a client with default options.

Customizing the ConfigCat Client

To customize the SDK's behavior, you can pass an additional (ConfigCatOptions) -> () parameter to the get() static factory method where the ConfigCatOptions class is used to set up the ConfigCat Client.

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.pollingMode = PollingModes.manualPoll()
options.logLevel = .info
}

These are the available options on the ConfigCatOptions class:

ArgumentsTypeDescription
dataGovernanceDataGovernanceOptional, defaults to global. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. More about Data Governance. Available options: global, euOnly.
configCacheConfigCache?Optional, sets a custom cache implementation for the client. More about cache.
pollingModePollingModeOptional, sets the polling mode for the client. More about polling modes.
sessionConfigurationURLSessionConfigurationOptional, sets a custom URLSessionConfiguration used by the HTTP calls.
baseUrlStringOptional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON.
flagOverridesOverrideDataSource?Optional, sets the local feature flag & setting overrides. More about feature flag overrides.
logLevelLogLevelOptional, sets the internal log level. More about logging..
defaultUserConfigCatUser?Optional, sets the default user. More about default user.
loggerConfigCatLoggerOptional, sets the logger implementation used by the SDK. More about logging
offlineBoolOptional, defaults to false. Indicates whether the SDK should be initialized in offline mode. More about offline mode.
hooksHooksOptional, used to subscribe events that the SDK sends in specific scenarios. More about hooks.
caution

We strongly recommend you to use the ConfigCatClient as a Singleton object in your application. The ConfigCatClient.get(sdkKey: <sdkKey>) static factory method constructs singleton client instances for your SDK keys. These clients can be closed all at once with the ConfigCatClient.closeAll() method or individually with client.close().

Anatomy of getValue()

ParametersDescription
keyREQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting.
defaultValueREQUIRED. This value will be returned in case of an error.
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
completionREQUIRED. Callback function to call, when the result is ready.
client.getValue(
for: "keyOfMySetting", // Setting Key
defaultValue: false, // Default value
user: ConfigCatUser(identifier: "#UNIQUE-USER-IDENTIFIER#") // Optional User Object
) { isMyAwesomeFeatureEnabled in
if isMyAwesomeFeatureEnabled {
doTheNewThing()
} else {
doTheOldThing()
}
}

// Or with async/await
let isMyAwesomeFeatureEnabled = await client.getValue(
for: "keyOfMySetting", // Setting Key
defaultValue: false, // Default value
user: ConfigCatUser(identifier: "#UNIQUE-USER-IDENTIFIER#") // Optional User Object

if isMyAwesomeFeatureEnabled {
doTheNewThing()
} else {
doTheOldThing()
}
caution

The following is only related to the SDK's generic-typed API which's only accessible from Swift.

It is important to provide an argument for the defaultValue parameter, specifically for the Value generic type parameter, that matches the type of the feature flag or setting you are evaluating. Please refer to the following table for the corresponding types.

Setting type mapping

Setting KindType parameter Value
On/Off ToggleBool / Bool?
TextString / String?
Whole NumberInt / Int?
Decimal NumberDouble / Double?

In addition to the types mentioned above, you also have the option to provide Any or Any? for the type parameter (or to use the getAnyValue method) regardless of the setting kind.

If you provide any other type for the type parameter, or if you specify an allowed type but it mismatches the setting kind, an error message will be logged and defaultValue will be returned.

When relying on type inference, be mindful of potential type mismatch issues, especially with number types. For example, await client.getValue(for: "keyOfMyDecimalSetting", defaultValue: 0) will return defaultValue (0) instead of the actual value of the decimal setting because the compiler infers the type as Int instead of Double.

To correctly evaluate a decimal setting, you should use:

let value = await client.getValue(for: "keyOfMyDecimalSetting", defaultValue: 0.0);

Anatomy of getValueDetails()

getValueDetails() is similar to getValue() but instead of returning the evaluated value only, it gives more detailed information about the evaluation result.

ParametersDescription
keyREQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting.
defaultValueREQUIRED. This value will be returned in case of an error.
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
client.getValueDetails(
for: "keyOfMySetting", // Setting Key
defaultValue: false, // Default value
user: ConfigCatUser(identifier: "#UNIQUE-USER-IDENTIFIER#") // Optional User Object
) { details in
// Use the details result
}

// Or with async/await
let details = await client.getValueDetails(
for: "keyOfMySetting", // Setting Key
defaultValue: false, // Default value
user: ConfigCatUser(identifier: "#UNIQUE-USER-IDENTIFIER#") // Optional User Object
caution

The following is only related to the SDK's generic-typed API which's only accessible from Swift.

It is important to provide an argument for the defaultValue parameter, specifically for the Value generic type parameter, that matches the type of the feature flag or setting you are evaluating. Please refer to this table for the corresponding types.

The details result contains the following information:

FieldTypeDescription
valueBool / String / Int / DoubleThe evaluated value of the feature flag or setting.
keyStringThe key of the evaluated feature flag or setting.
isDefaultValueBoolTrue when the default value passed to getValueDetails() is returned due to an error.
errorString?In case of an error, this property contains the error message.
userConfigCatUser?The User Object that was used for evaluation.
matchedPercentageOptionPercentageOption?The Percentage Option (if any) that was used to select the evaluated value.
matchedTargetingRuleTargetingRule?The Targeting Rule (if any) that matched during the evaluation and was used to return the evaluated value.
fetchTimeDateThe last download time of the current config.

Snapshots and synchronous feature flag evaluation

The ConfigCat client provides only asynchronous methods for evaluating feature flags and settings because these operations may involve network communication (downloading config data from the ConfigCat CDN servers), which is necessarily an asynchronous operation.

However, there may be use cases where synchronous evaluation is preferable, thus, since v10.0.0, the Swift SDK provides a way to synchronously evaluate feature flags and settings via Snapshots.

Using the snapshot() method, you can capture the current state of the ConfigCat client (including the latest downloaded config data) and you can use the resulting snapshot object to synchronously evaluate feature flags and settings based on the captured state:

let snapshot = configCatClient.snapshot()

let isMyFeatureEnabled = snapshot.getValue(for: "isMyFeatureEnabled", defaultValue: false)

Snapshots are created from the actual state of the SDK; therefore it's crucial to know whether the SDK has valid feature flag data to work on. To determine whether it's safe to create snapshots, the SDK provides an onClientReady hook. It accepts a state enum parameter to give details about the SDK's initialization state.

client.hooks.addOnReady { state in
// the state parameter tells what is the SDK's initialization state
}

The possible state values:

  • noFlagData: The SDK has no feature flag data to work on (it didn't get anything from the cache or from the network)
  • hasLocalOverrideFlagDataOnly: The SDK was initialized with localOnly flag overrides.
  • hasCachedFlagDataOnly: The SDK has feature flag data only from the cache. This can happen when the SDK is configured with manualPoll() and there wasn't a client.forceRefresh() call yet. Another example could be an SDK configured with autoPoll(), but it can't reach the ConfigCat CDN so it falls back to the cache.
  • hasUpToDateFlagData: The SDK is initialized with up-to-date feature flag data.

The SDK's state is also accessible via the waitForReady() awaitable method, which asynchronously waits for the onClientReady hook to fire and returns with the SDK's initialization state.

let state = await client.waitForReady()

User Object

The User Object is essential if you'd like to use ConfigCat's Targeting feature.

let user = ConfigCatUser(identifier: "#UNIQUE-USER-IDENTIFIER#")
let user = ConfigCatUser(identifier: "[email protected]")
ArgumentsDescription
identifierREQUIRED. Unique identifier of a user in your application. Can be any value, even an email address.
emailOptional parameter for easier Targeting Rule definitions.
countryOptional parameter for easier Targeting Rule definitions.
customOptional dictionary for custom attributes of a user for advanced Targeting Rule definitions. e.g. User role, Subscription type.
let user = ConfigCatUser(identifier: "#UNIQUE-USER-IDENTIFIER#",
email: "[email protected]",
country: "United Kingdom",
custom: ["SubscriptionType":"Pro", "UserRole":"Admin"])

The custom map also allows attribute values other than String values:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let registeredAt = dateFormatter.date(from:"2023-03-31T23:59:59.999Z")!

let user = ConfigCatUser(identifier: "#UNIQUE-USER-IDENTIFIER#",
email: "[email protected]",
country: "United Kingdom",
custom: ["Rating":4.5, "RegisteredAt":registeredAt, "Roles": ["Role1", "Role2"]])

User Object Attribute Types

All comparators support String values as User Object attribute (in some cases they need to be provided in a specific format though, see below), but some of them also support other types of values. It depends on the comparator how the values will be handled. The following rules apply:

Text-based comparators (EQUALS, IS ONE OF, etc.)

  • accept String values,
  • all other values are automatically converted to String (a warning will be logged but evaluation will continue as normal).

SemVer-based comparators (IS ONE OF, <, >=, etc.)

  • accept String values containing a properly formatted, valid semver value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped).

Number-based comparators (=, <, >=, etc.)

  • accept Int, UInt, Double, or Float values,
  • accept String values containing a properly formatted, valid Double value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped).

Date time-based comparators (BEFORE / AFTER)

  • accept Date values, which are automatically converted to a second-based Unix timestamp,
  • accept Int, UInt, Double, or Float values representing a second-based Unix timestamp,
  • accept String values containing a properly formatted, valid Double value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped).

String array-based comparators (ARRAY CONTAINS ANY OF / ARRAY NOT CONTAINS ANY OF)

  • accept arrays of String,
  • accept String values containing a valid JSON string which can be deserialized to an array of String,
  • all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped).

Default user

There's an option to set a default User Object that will be used at feature flag and setting evaluation. It can be useful when your application has a single user only, or rarely switches users.

You can set the default User Object either on SDK initialization:

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.defaultUser = ConfigCatUser(identifier: "[email protected]")
}

or with the setDefaultUser() method of the ConfigCat client.

client.setDefaultUser(user: ConfigCatUser(identifier: "[email protected]"))

Whenever the getValue(), getValueDetails(), getAllValues(), or getAllVariationIds() methods are called without an explicit user parameter, the SDK will automatically use the default user as a User Object.

let user = ConfigCatUser(identifier: "[email protected]")
client.setDefaultUser(user)

// The default user will be used at the evaluation process.
let value = await client.getValue(for: "keyOfMySetting", defaultValue: false)

When the user parameter is specified on the requesting method, it takes precedence over the default user.

et user = ConfigCatUser(identifier: "[email protected]")
client.setDefaultUser(user)

let otherUser = ConfigCatUser(identifier: "[email protected]")

// otherUser will be used at the evaluation process.
let value = await client.getValue(for: 'keyOfMySetting', defaultValue: false, user: otherUser)

For deleting the default user, you can do the following:

client.clearDefaultUser()

getAllKeys()

You can get all the setting keys from your config JSON by calling the getAllKeys() method of the ConfigCatClient.

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#")

// Completion callback
client.getAllKeys() { keys in
// use keys
}

// Async/await
let keys = await client.getAllKeys()

getAllValues()

Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.

ParametersDescription
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#")
let user = ConfigCatUser(identifier: "#UNIQUE-USER-IDENTIFIER#")

// Completion callback
client.getAllValues(
user: user// Optional User Object
) { allValues in
// use allValues
}

// Async/await
let allValues = await client.getAllValues(
user: user // Optional User Object
)

Polling Modes

The ConfigCat SDK supports 3 different polling mechanisms to acquire the setting values from ConfigCat. After latest setting values are downloaded, they are stored in the internal cache, then all getValue() calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle.
More about polling modes.

Auto polling (default)

The ConfigCat SDK downloads the latest values and stores them automatically every 60 seconds.

Use the the autoPollIntervalInSeconds option parameter of the PollingModes.autoPoll() to change the polling interval.

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.pollingMode = PollingModes.autoPoll(autoPollIntervalInSeconds: 120 /* polling interval in seconds */)
}

Available options:

Option ParameterDescriptionDefault
autoPollIntervalInSecondsPolling interval.60
maxInitWaitTimeInSecondsMaximum waiting time between the client initialization and the first config acquisition in secconds.5

Lazy loading

When calling getValue(), the ConfigCat SDK downloads the latest setting values if they are not present or expired in the cache. In this case getValue() will return the setting value after the cache is updated.

Use the cacheRefreshIntervalInSeconds option parameter of the PollingModes.lazyLoad() to set cache lifetime.

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.pollingMode = PollingModes.lazyLoad(cacheRefreshIntervalInSeconds: 120 /* the cache will expire in 120 seconds */)
}

Available options:

Option ParameterDescriptionDefault
cacheRefreshIntervalInSecondsCache TTL.60

Manual polling

Manual polling gives you full control over when the config JSON (with the setting values) is downloaded. ConfigCat SDK will not update them automatically. Calling refresh() is your application's responsibility.

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.pollingMode = PollingModes.manualPoll()
}

// Completion callback
client.forceRefresh() { _ in
// The client uses the latest config JSON
}

// Async/await
await client.forceRefresh()

getValue() returns defaultValue if the cache is empty. Call refresh() to update the cache.

Hooks

With the following hooks you can subscribe to particular events fired by the SDK:

  • onClientReady(): This event is sent when the SDK reaches the ready state. If the SDK is initialized with lazy load or manual polling it's considered ready right after instantiation. If it's using auto polling, the ready state is reached when the SDK has a valid config JSON loaded into memory either from cache or from HTTP. If the config couldn't be loaded neither from cache nor from HTTP the onClientReady event fires when the auto polling's maxInitWaitTimeInSeconds is reached.

  • onConfigChanged([String: Setting]): This event is sent when the SDK loads a valid config JSON into memory from cache, and each subsequent time when the loaded config JSON changes via HTTP.

  • onFlagEvaluated(EvaluationDetails): This event is sent each time when the SDK evaluates a feature flag or setting. The event sends the same evaluation details that you would get from getValueDetails().

  • onError(String): This event is sent when an error occurs within the ConfigCat SDK.

You can subscribe to these events either on SDK initialization:

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.hooks.addOnFlagEvaluated { details in
/* handle the event */
}
}

or with the hooks property of the ConfigCat client:

client.hooks.addOnFlagEvaluated { details in
/* handle the event */
}

Online / Offline mode

In cases when you'd want to prevent the SDK from making HTTP calls, you can put it in offline mode:

client.setOffline()

In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.

To put the SDK back in online mode, you can do the following:

client.setOnline()

With client.isOffline you can check whether the SDK is in offline mode.

Flag Overrides

With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:

  • Local only (OverrideBehaviour.localOnly): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources.

  • Local over remote (OverrideBehaviour.localOverRemote): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence.

  • Remote over local (OverrideBehaviour.remoteOverLocal): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.

You can set up the SDK to load your feature flag & setting overrides from a [String: Any] dictionary.

let dictionary:[String: Any] = [
"enabledFeature": true,
"disabledFeature": false,
"intSetting": 5,
"doubleSetting": 3.14,
"stringSetting": "test"
]

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.flagOverrides = LocalDictionaryDataSource(source: dictionary, behaviour: .localOnly)
}

Cache

The SDK uses UserDefaults as the default cache to store the downloaded config JSON.

If you want to turn off the default behavior, you can set the SDK's cache to nil or to your own cache implementation.

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.configCache = nil
}

Custom cache

You have the option to inject your custom cache implementation into the client. All you have to do is to conform the ConfigCache protocol:

@import ConfigCat

public class MyCustomCache: ConfigCache {
public func read(key: String) throws -> String {
// here you have to return with the cached value
}

public func write(key: String, value: String) throws {
// here you have to store the new value in the cache
}
}

Then you can use your custom cache implementation at the SDK's initialization:

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.configCache = MyCustomCache()
}
info

The Swift SDK supports shared caching. You can read more about this feature and the required minimum SDK versions here.

Force refresh

Call the forceRefresh() method on the client to download the latest config JSON and update the cache.

Using ConfigCat behind a proxy

Provide your own network credentials (username/password), and proxy server settings (proxy server/port) by adding a ProxyDictionary to the ConfigCat's URLSessionConfiguration.

let proxyHost = "127.0.0.1"
let proxyPort = 8080
let proxyUser = "user"
let proxyPassword = "password"

let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.connectionProxyDictionary = [
kCFNetworkProxiesHTTPEnable: true,
kCFNetworkProxiesHTTPProxy: proxyHost,
kCFNetworkProxiesHTTPPort: proxyPort,
kCFNetworkProxiesHTTPSEnable: true,
kCFNetworkProxiesHTTPSProxy: proxyHost,
kCFNetworkProxiesHTTPSPort: proxyPort,
kCFProxyUsernameKey: proxyUser, // Optional
kCFProxyPasswordKey: proxyPassword // Optional
]

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.sessionConfiguration = sessionConfiguration
}

Changing the default HTTP timeout

Set the maximum wait time for a ConfigCat HTTP response by changing the timeoutIntervalForRequest of the ConfigCat's URLSessionConfiguration. The default timeoutIntervalForRequest is 60 seconds.

let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.timeoutIntervalForRequest = 10 // Timeout in seconds

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.sessionConfiguration = sessionConfiguration
}

Logging

The default logger used by the SDK is using the Unified Logging System. For more information about Unified Logging please visit Apple's developer page or check Session 721 - Unified Logging and Activity Tracing from WWDC 2016.

You can override the default logger with your custom implementation via the logger client option. The custom implementation must conform the ConfigCatLogger protocol.

@import ConfigCat

class MyCustomLogger: ConfigCatLogger {
func debug(message: String) {
// write the debug logs
}

func info(message: String) {
// write the info logs
}

func warning(message: String) {
// write the warning logs
}

func error(message: String) {
// write the error logs
}
}

Then you can use your custom logger implementation at the SDK's initialization:

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.logger = MyCustomLogger()
}

Log level

You can change the verbosity of the logs by setting the logLevel option.

let client = ConfigCatClient.get(sdkKey: "#YOUR-SDK-KEY#") { options in
options.logLevel = .info
}

Available log levels:

LevelDescription
.nologTurn the ConfigCat logging off.
.errorOnly error level events are logged.
.warningDefault. Errors and Warnings are logged.
.infoErrors, Warnings and feature flag evaluation is logged.
.debugAll of the above plus debug info is logged. Debug logs can be different for other SDKs.

Info level logging helps to inspect the feature flag evaluation process.
Example log entries:

[5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":"<SOME USERID>","version":"1.0.0","Email":"[email protected]","Country":"CountryID"}'
Evaluating targeting rules and applying the first match if any:
- IF User.Email CONTAINS ANY OF ['@something.com'] THEN 'false' => no match
- IF User.Email CONTAINS ANY OF ['@example.com'] THEN 'true' => MATCH, applying rule
Returning 'true'.

Sensitive information handling

The frontend/mobile SDKs are running in your users' browsers/devices. The SDK is downloading a config JSON file from ConfigCat's CDN servers. The URL path for this config JSON file contains your SDK key, so the SDK key and the content of your config JSON file (feature flag keys, feature flag values, Targeting Rules, % rules) can be visible to your users. In ConfigCat, all SDK keys are read-only. They only allow downloading your config JSON files, but nobody can make any changes with them in your ConfigCat account.

If you do not want to expose the SDK key or the content of the config JSON file, we recommend using the SDK in your backend components only. You can always create a backend endpoint using the ConfigCat SDK that can evaluate feature flags for a specific user, and call that backend endpoint from your frontend/mobile applications.

Also, we recommend using confidential targeting comparators in the Targeting Rules of those feature flags that are used in the frontend/mobile SDKs.

Sample App

Check out our Sample Application how they use the ConfigCat SDK