ContentstackConfig

View as Markdown

ContentstackConfig

ContentstackConfig contains the decoding and network settings of a Stack. Create one with ContentstackConfig(), set its properties, and pass it as the config argument of the stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:) method of Contentstack. Use this struct to

  • decode the dates of your content with your own strategy or time zone
  • change the network session, for example its timeouts or extra headers
  • answer TLS authentication challenges with your own delegate, for example to pin a certificate

A stack created without a config uses ContentstackConfig.default.

Known issue: the SDK never sends the early access header that earlyAccess and setEarlyAccess(_:) describe, so early access features stay off. To request them, add the x-header-ea header to sessionConfiguration.httpAdditionalHeaders instead.

Class-Level Properties

PropertyTypeAccessDefaultDescription
defaultContentstackConfigRead-only (static)A config with the defaults belowConfig that a stack uses when you pass none.
earlyAccess[String]?Read/writenilEarly access feature names. The SDK does not send them today.
dateDecodingStrategyJSONDecoder.DateDecodingStrategy?Read/writenilReplaces the date decoding of the SDK.
timeZoneTimeZone?Read/writenil, which means UTCTime zone of date strings that carry no offset.
sessionConfigurationURLSessionConfigurationRead/writeA new URLSessionConfiguration.defaultSettings of the network session, such as timeouts and headers.
urlSessionDelegateCSURLSessionDelegate?Read/writenilObject that answers TLS authentication challenges.

Class-Level Notes

When the stack reads the config.

  • ContentstackConfig is a struct. Declare it with var to set its properties.
  • stack(...) reads the config once, when it creates the stack. A later change to the config does not reach that stack.

Dates.

  • By default the SDK decodes ISO 8601 date strings. The SDK reads a date string with no offset, such as 2026-01-15, in timeZone, or in UTC when timeZone is nil.
  • dateDecodingStrategy replaces that decoding for every response of the stack. timeZone then has no effect.
  • The SDK decodes global fields with a separate decoder, so neither setting applies to them.

Network session.

  • The stack creates its own URLSession from sessionConfiguration, with urlSessionDelegate as the delegate when you set one.
  • The SDK adds the X-User-Agent and User-Agent headers and, for a stack with a branch, the branch header. It writes them into sessionConfiguration.httpAdditionalHeaders of the config you pass.
  • Headers that you put in httpAdditionalHeaders go out with every request of the stack. They replace the X-User-Agent and User-Agent values of the SDK, but the branch argument of the stack replaces a branch header of your own.
  • The SDK sets no timeout of its own. Set timeoutIntervalForRequest on sessionConfiguration to change the system default.
  • Because the SDK writes into sessionConfiguration, stacks that share one config also share those headers. The stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:) page describes the effect on branches. Give each stack its own ContentstackConfig().

CSURLSessionDelegate

CSURLSessionDelegate is the protocol of urlSessionDelegate. It extends NSObjectProtocol and URLSessionDelegate, so the object that adopts it is an NSObject subclass. The list below names its two requirements.

  • urlSession(_:didReceive:completionHandler:), required. Receives session-level challenges, such as server trust. Evaluate challenge.protectionSpace.serverTrust and call the completion handler with a disposition and a credential.
  • urlSession(_:task:didReceive:completionHandler:), optional. Receives task-level challenges.

The session retains the delegate for the life of the stack.

Method Index

Method NameReturnsDescription
init()A new config with the default values.Creates a config to change and pass to a stack.
setEarlyAccess(_:)Nothing. The config stores the names in earlyAccess.Stores the early access feature names.

Class-Level Snippet

The snippet below creates a stack with a 30-second request timeout, a fixed time zone, and a delegate that checks the server certificate.

Configure the timeout, time zone and TLS delegate of a stack

import Foundation
import ContentstackSwift

final class TrustChecker: NSObject, CSURLSessionDelegate {
    func urlSession(_ session: URLSession,
                    didReceive challenge: URLAuthenticationChallenge,
                    completionHandler: @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        // Evaluate challenge.protectionSpace.serverTrust here, for example against a pinned certificate.
        completionHandler(.performDefaultHandling, nil)
    }
}

var config = ContentstackConfig()
config.sessionConfiguration.timeoutIntervalForRequest = 30
config.timeZone = TimeZone(identifier: "America/New_York")
config.urlSessionDelegate = TrustChecker()

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT", config: config)
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        switch result {
        case .success(let entry):
            print(entry.title, entry.updatedAt ?? "no date")
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Methods

Each method of the ContentstackConfig struct has its own section below, with its parameters, validation rules, behavior, and examples.

init()

init() creates a config with the default value of every property, ready for you to change and pass to a stack.

This method takes no parameters.

Returns: ContentstackConfig. A new config with the default values.

Validation

  • There is no client-side validation.

Behavior

  • Client-side only. init() makes no request.
  • The new config has nil for earlyAccess, dateDecodingStrategy, timeZone and urlSessionDelegate, and a new URLSessionConfiguration.default object for sessionConfiguration.
  • Each config from init() has its own sessionConfiguration object, unlike ContentstackConfig.default, which every stack created without a config shares. Pass a new config to each stack, so that the headers of one stack stay out of the requests of another.

Example

Basic usage: create a config, change it and pass it to a stack

import ContentstackSwift

var config = ContentstackConfig()
config.sessionConfiguration.httpAdditionalHeaders = ["x-app-name": "my-ios-app"]

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT", config: config)
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        switch result {
        case .success(let entry):
            print(entry.title)
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

setEarlyAccess(_:)

setEarlyAccess(_:) stores the names of the early access features that a stack should request.

NameTypeDescription
earlyAccess (required)[String]

Early access feature names to request.

Default: Not applicable

Returns: Void. Nothing. The config stores the names in earlyAccess.

Validation

  • There is no client-side validation. The SDK does not check the names against a list of features.
  • setEarlyAccess(_:) is a mutating method, so call it on a config that you declared with var. On a let constant the call does not compile.

Behavior

  • Client-side only. setEarlyAccess(_:) makes no request.
  • The method replaces the value of the earlyAccess property. Setting config.earlyAccess directly has the same effect.
  • The SDK does not send the stored names, so the stack requests no early access feature. The ContentstackConfig class page records this as a known issue.
  • To request the features, join the names with commas and set them as the x-header-ea header in sessionConfiguration.httpAdditionalHeaders, as the second example below does.

Example

Basic usage: store early access feature names

import ContentstackSwift

var config = ContentstackConfig()
config.setEarlyAccess(["FEATURE_ONE", "FEATURE_TWO"])
print(config.earlyAccess ?? [])

Request early access features through the session headers

import ContentstackSwift

let features = ["FEATURE_ONE", "FEATURE_TWO"]
var config = ContentstackConfig()
config.setEarlyAccess(features)
// The SDK sends headers from httpAdditionalHeaders with every request of the stack.
config.sessionConfiguration.httpAdditionalHeaders = ["x-header-ea": features.joined(separator: ",")]

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT", config: config)
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        switch result {
        case .success(let entry):
            print(entry.title)
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }