Contentstack

View as Markdown

Contentstack

Contentstack is the entry point of the Swift Delivery SDK. It holds only static methods, so you call them on the type and never create an instance. Use this struct to

  • create the Stack that every other object comes from
  • look up the API host of a Contentstack region, for example to call another Contentstack API from your app
  • render the embedded entries and assets of an HTML rich text field

Class-Level Notes

Creating a stack makes no request.

  • stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:) only stores the credentials and settings. The first request goes out when you call fetch(_:), find(_:) or sync(_:syncTypes:then:) on an object that the stack creates.
  • The SDK does not check the API key, delivery token or environment when it creates the stack. A wrong value surfaces as an APIError from the first request.

How the SDK selects the delivery host.

  • A host other than the default Host.delivery (cdn.contentstack.io) always wins. Otherwise the SDK uses the delivery host of region.
  • The stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:) method describes the full rules, including the fallback when the device has no cached regions registry. The ContentstackRegion table below lists the fallback host for each region.

Regions registry.

  • getContentstackEndpoint(region:service:omitHttps:) and getContentstackEndpoints(region:omitHttps:) read the Contentstack regions registry, a JSON file at https://artifacts.contentstack.com/regions.json. The SDK does not ship a copy.
  • The SDK reads the registry from memory first, then from its copy in the caches directory of the app, and downloads it only when neither exists. It downloads at most once for each app launch.
  • A download blocks the calling thread for up to about 12 seconds, so call these methods off the main thread.

Method Index

The tables below group the methods by task.

Create a stack. The method below makes no request.

Method NameReturnsDescription
stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:)A new stack for the given credentials and settings.Creates the stack for one environment.

Look up region endpoints. The methods below read the regions registry and download it when the device has no copy.

Method NameReturnsDescription
getContentstackEndpoint(region:service:omitHttps:)The URL for the region and service.Looks up the URL of one Contentstack API in a region.
getContentstackEndpoints(region:omitHttps:)A [String: String] dictionary that maps each service name of the region to its URL.Looks up the URLs of all Contentstack APIs in a region.

Render HTML rich text. Available as static methods of Contentstack.Utils. The methods below make no request.

Method NameReturnsDescription
Utils.render(content:option:)The HTML with each embedded object replaced by its rendered HTML.Renders the embedded objects of one HTML string.
Utils.render(contents:option:)The rendered HTML strings, in the order of the input.Renders the embedded objects of several HTML strings.

ContentstackRegion

ContentstackRegion specifies the region of your stack. Pass it as the region argument of stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:). The raw value is also a valid region argument for the endpoint lookup methods, for example ContentstackRegion.azure_na.rawValue.

The table below lists every case and the delivery host the SDK uses when the device has no cached registry.

CaseRaw valueMeaning
us"us"AWS North America. Uses cdn.contentstack.io. The default.
eu"eu"AWS Europe. Uses eu-cdn.contentstack.com.
au"au"AWS Australia. Uses au-cdn.contentstack.com.
azure_na"azure-na"Azure North America. Uses azure-na-cdn.contentstack.com.
azure_eu"azure-eu"Azure Europe. Uses azure-eu-cdn.contentstack.com.
gcp_na"gcp-na"Google Cloud North America. Uses gcp-na-cdn.contentstack.com.
gcp_eu"gcp-eu"Google Cloud Europe. Uses gcp-eu-cdn.contentstack.com.

Host

Host contains one constant, the default delivery host. The table below describes it.

PropertyTypeAccessDefaultDescription
deliveryStringRead-only (static)"cdn.contentstack.io"Default host of a stack, the AWS North America delivery host.

EndpointError

The endpoint lookup methods throw EndpointError. It conforms to Error, LocalizedError, CustomStringConvertible and Equatable, so you can compare a caught error with a case. The table below lists each case.

CaseWhen the SDK throws it
emptyRegionregion is empty or holds only whitespace.
invalidRegion(String)region matches no region ID or alias in the registry. The associated value is the region you passed.
serviceNotFound(service: String, region: String)The region exists, but the registry lists no URL for service in it.
regionsUnavailableThe device has no copy of the registry and the download failed, or a download already failed earlier in this app launch.

ContentstackEndpoint

ContentstackEndpoint is the enum behind the endpoint lookup methods of Contentstack. The table below lists its members, which are all static.

MemberTypeDescription
regionsURLStringThe registry URL, https://artifacts.contentstack.com/regions.json. Read-only.
getContentstackEndpoint(_:service:omitHttps:allowDownload:)Throwing function that returns StringDoes the same as getContentstackEndpoint(region:service:omitHttps:). Pass allowDownload: false to read only the cached registry and never download it. allowDownload defaults to true.
getContentstackEndpoints(_:omitHttps:allowDownload:)Throwing function that returns [String: String]Does the same as getContentstackEndpoints(region:omitHttps:), with the same allowDownload argument.

Endpoint

Endpoint defines the API path of each kind of resource. The endpoint static property of SyncStack and of every model type returns one, and the SDK builds the request path from it. No SDK method takes an Endpoint argument. The table below lists every case.

CaseRaw valueMeaning
stack"stack"Stack path. No SDK request uses it.
contenttype"content_types"Content types, and the parent path of entries.
entries"entries"Entries of a content type.
assets"assets"Assets.
sync"stacks/sync"The Sync API.
taxnomies"taxonomies"Entries queried by taxonomy. The SDK spells the case name taxnomies.
globalfields"global_fields"Global fields.

Endpoint has one property, pathComponent (String, read-only), which returns the raw value.

Contentstack.Utils and Option

Contentstack.Utils contains the two render methods in the Method Index above. They take an Option, which comes from the ContentstackUtils package that the SDK depends on. Add import ContentstackUtils to any file that names Option, because import ContentstackSwift does not make it visible.

Option is an open class. The members below come from ContentstackUtils 1.3.4, the version that the SDK pins in its package manifest. They control what render writes for each embedded object.

  • Option() creates an option with no entry. render then removes every embedded object from the HTML.
  • Option(entry:) takes a value that conforms to the EntryEmbedable protocol of ContentstackUtils. Its embeddedItems dictionary contains the embedded objects, and render replaces each embedded object of the HTML whose UID and content type UID match one of them.
  • renderItem(embeddedObject:metadata:) returns the HTML for one embedded object. Subclass Option and override it to write your own HTML. The default writes a <div> for a block entry, a <span> for an inline entry, an <a> for a link, and an <img> for an asset.
  • renderMark(markType:text:) and renderNode(nodeType:node:next:) apply to JSON Rich Text Editor content only. The render methods do not call them.

Class-Level Snippet

The snippet below creates a stack in the EU region and fetches one entry from it.

Create a stack for the EU region and fetch an entry

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT", region: .eu)
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) from \(stack.host)")
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Methods

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

Utils.render(content:option:)

Utils.render(content:option:) replaces each embedded entry and asset in the HTML of a rich text field with HTML that you control.

NameTypeDescription
content (required)String

HTML of one HTML Rich Text Editor field.

Default: Not applicable
option (required)Option

Embedded objects and the HTML to write for them.

Default: Not applicable

Returns: String. The HTML with each embedded object replaced by its rendered HTML.

Validation

  • Utils.render(content:option:) is a throwing function, so call it with try. It throws the error of the HTML parser when the parser cannot read content.
  • There is no other client-side validation. An empty content returns an empty string.

Behavior

  • Client-side only. Utils.render(content:option:) makes no request. Fetch the entry first.
  • The SDK finds each element of content whose class attribute contains embedded-entry or embedded-asset. It reads the UID and content type UID of the object from the data-sys-entry-uid or data-sys-asset-uid and data-sys-content-type-uid attributes.
  • For each element, one of the two outcomes below applies, depending on option:
    • When option holds an entry, through Option(entry:), the SDK looks in its embeddedItems for an object with the same UID and content type UID. On a match, the SDK replaces the element with the HTML that renderItem(embeddedObject:metadata:) returns.
    • Otherwise the SDK removes the element. Option() with no entry removes every embedded object.
  • The SDK keeps the rest of content as it is.
  • Option comes from the ContentstackUtils package, so the file needs import ContentstackUtils. The Contentstack class page describes Option and its default HTML.
  • To render several fields at once, use the Utils.render(contents:option:) method.

Example

Basic usage: remove the embedded objects from a fetched rich text field

import ContentstackSwift
import ContentstackUtils

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        switch result {
        case .success(let entry):
            let html = entry.fields?["rich_text_editor"] as? String ?? ""
            do {
                // Option() has no entry, so the SDK removes every embedded object.
                print(try Contentstack.Utils.render(content: html, option: Option()))
            } catch {
                print("Could not parse the HTML: \(error)")
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Custom HTML: render an embedded entry as a link

import ContentstackSwift
import ContentstackUtils

// One embedded entry that your app reads from the fetched entry.
final class LinkedEntry: EmbeddedEntry {
    static var contentTypeUid = "CONTENT_TYPE_UID"
    let uid: String
    let contentTypeUID = "CONTENT_TYPE_UID"
    let fields: [String: Any]? = nil
    let title: String
    init(uid: String, title: String) {
        self.uid = uid
        self.title = title
    }
}

struct RichTextItems: EntryEmbedable {
    let embeddedItems: [AnyHashable: [EmbeddedObject]]?
}

final class LinkRenderer: Option {
    override func renderItem(embeddedObject: EmbeddedObject, metadata: Metadata) -> String? {
        if let entry = embeddedObject as? EmbeddedEntry {
            return "<a href=\"https://www.example.com/articles/\(entry.uid)\">\(entry.title)</a>"
        }
        return super.renderItem(embeddedObject: embeddedObject, metadata: metadata)
    }
}

let html = """
<p>Read <span class="embedded-entry inline-entry" data-sys-entry-uid="ENTRY_UID" \
data-sys-content-type-uid="CONTENT_TYPE_UID" sys-style-type="inline"></span> next.</p>
"""
let items = RichTextItems(embeddedItems: ["rich_text_editor": [LinkedEntry(uid: "ENTRY_UID", title: "Getting started")]])
do {
    let rendered = try Contentstack.Utils.render(content: html, option: LinkRenderer(entry: items))
    print(rendered) // <p>Read <a href="https://www.example.com/articles/ENTRY_UID">Getting started</a> next.</p>
} catch {
    print(error)
}

Utils.render(contents:option:)

Utils.render(contents:option:) replaces the embedded entries and assets in several HTML strings, such as the values of a multiple rich text field, with HTML that you control.

NameTypeDescription
contents (required)[String]

HTML strings of HTML Rich Text Editor fields.

Default: Not applicable
option (required)Option

Embedded objects and the HTML to write for them.

Default: Not applicable

Returns: Array<String>. The rendered HTML strings, in the order of the input.

Validation

  • Utils.render(contents:option:) is a throwing function, so call it with try. It throws the error of the HTML parser when the parser cannot read one of the strings, and returns no partial result.
  • There is no other client-side validation. An empty array returns an empty array.

Behavior

  • Client-side only. Utils.render(contents:option:) makes no request.
  • The SDK runs the Utils.render(content:option:) method on each string, with the same option, and returns the results in the same order. That page lists the rules for replacing or removing each embedded object.
  • Option comes from the ContentstackUtils package, so the file needs import ContentstackUtils.

Example

Basic usage: render every value of a multiple rich text field

import ContentstackSwift
import ContentstackUtils

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        switch result {
        case .success(let entry):
            let sections = entry.fields?["sections"] as? [String] ?? []
            do {
                let rendered = try Contentstack.Utils.render(contents: sections, option: Option())
                rendered.forEach { print($0) }
            } catch {
                print("Could not parse the HTML: \(error)")
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

getContentstackEndpoint(region:service:omitHttps:)

getContentstackEndpoint(region:service:omitHttps:) returns the URL of one Contentstack API, such as the Content Delivery API, in the region you name.

NameTypeDescription
region (required)String

Region ID or alias, for example "eu".

Default: Not applicable
service (required)String

Service name, for example "contentDelivery".

Default: Not applicable
omitHttpsBool

Returns the bare host, without https://.

Default: false

Returns: String. The URL for the region and service.

Validation

  • getContentstackEndpoint(region:service:omitHttps:) is a throwing function, so call it with try. It throws an EndpointError:
    • emptyRegion if region is empty or holds only whitespace, because the SDK cannot match it to a region.
    • invalidRegion if region matches no region ID or alias in the registry.
    • serviceNotFound if the region exists but the registry lists no URL for service in it.
    • regionsUnavailable if the device has no copy of the registry and the download fails.
  • The SDK does not check service against a fixed list. Any name that the registry lists for the region works.

Behavior

  • The SDK reads the URL from the Contentstack regions registry, in the order below: 1. The copy in memory, from an earlier call in this app launch. 2. The copy in the caches directory of the app, from an earlier launch. 3. A download from https://artifacts.contentstack.com/regions.json, which the SDK then keeps in memory and in the caches directory.
  • The SDK downloads the registry at most once for each app launch. It also tries that one download when region is missing from the copy it holds, in case Contentstack added a region since then.
  • After a failed download, every later call in the same app launch throws regionsUnavailable until the app restarts, unless the caches directory holds a copy.
  • The download blocks the calling thread until it ends, for up to about 12 seconds. Call this method off the main thread, for example in a Task.
  • Region matching does not distinguish upper and lower case, trims surrounding whitespace, and treats - and _ alike. For example, "azure-na", "AZURE_NA" and ContentstackRegion.azure_na.rawValue all match Azure North America. "na", "us" and "aws-na" all match AWS North America.
  • The service names come from the registry, for example contentDelivery, contentManagement, graphqlDelivery, images and preview. To list every service of a region, use the getContentstackEndpoints(region:omitHttps:) method.
  • The method does not change any stack. To send a stack's requests to the host it returns, pass the host as the host argument of the stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:) method, with omitHttps: true.

Example

Basic usage: look up the Content Delivery API URL for a region

import ContentstackSwift

do {
    let url = try Contentstack.getContentstackEndpoint(region: "eu", service: "contentDelivery")
    print(url)
} catch let error as EndpointError {
    print("Endpoint lookup failed: \(error)")
} catch {
    print(error)
}

All parameters: get a bare host and create a stack with it

import ContentstackSwift

Task {
    // The first lookup in an app launch can download the registry, so it runs off the main thread.
    do {
        let host = try Contentstack.getContentstackEndpoint(region: ContentstackRegion.azure_eu.rawValue,
                                                            service: "contentDelivery",
                                                            omitHttps: true)
        let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT",
                                       region: .azure_eu, host: host)
        let entry: EntryModel = try await stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID").fetch()
        print(entry.title)
    } catch {
        print(error)
    }
}

Error handling: react to each EndpointError case

import ContentstackSwift

do {
    let url = try Contentstack.getContentstackEndpoint(region: "eu", service: "graphqlDelivery")
    print(url)
} catch EndpointError.emptyRegion {
    print("Pass a region")
} catch EndpointError.invalidRegion(let region) {
    print("Unknown region: \(region)")
} catch EndpointError.serviceNotFound(let service, let region) {
    print("\(service) is not available in \(region)")
} catch EndpointError.regionsUnavailable {
    print("The SDK could not load the regions registry. Check the network connection.")
} catch {
    print(error)
}

getContentstackEndpoints(region:omitHttps:)

getContentstackEndpoints(region:omitHttps:) returns a dictionary of the service names and URLs of every Contentstack API in the region you name.

NameTypeDescription
region (required)String

Region ID or alias, for example "eu".

Default: Not applicable
omitHttpsBool

Returns bare hosts, without https://.

Default: false

Returns: Dictionary. A [String: String] dictionary that maps each service name of the region to its URL.

Validation

  • getContentstackEndpoints(region:omitHttps:) is a throwing function, so call it with try. It throws an EndpointError:
    • emptyRegion if region is empty or holds only whitespace, because the SDK cannot match it to a region.
    • invalidRegion if region matches no region ID or alias in the registry, or the registry lists no services for it.
    • regionsUnavailable if the device has no copy of the registry and the download fails.

Behavior

  • The SDK reads the regions registry from memory, then from the caches directory of the app, and downloads it at most once for each app launch.
  • The getContentstackEndpoint(region:service:omitHttps:) method describes the order and the region matching rules, which apply here too.
  • The download blocks the calling thread for up to about 12 seconds. Call this method off the main thread.
  • The dictionary contains only the services that the registry lists for the region. Not every region offers every service, so check a key before you use it.
  • The keys are service names, for example contentDelivery, contentManagement, graphqlDelivery, images and preview.

Example

Basic usage: list every API URL of a region

import ContentstackSwift

do {
    let endpoints = try Contentstack.getContentstackEndpoints(region: "eu")
    for (service, url) in endpoints.sorted(by: { $0.key < $1.key }) {
        print("\(service): \(url)")
    }
} catch let error as EndpointError {
    print("Endpoint lookup failed: \(error)")
} catch {
    print(error)
}

All parameters: read the bare delivery and image hosts of a region

import ContentstackSwift

do {
    let hosts = try Contentstack.getContentstackEndpoints(region: ContentstackRegion.gcp_na.rawValue, omitHttps: true)
    if let deliveryHost = hosts["contentDelivery"], let imagesHost = hosts["images"] {
        print("Delivery: \(deliveryHost), images: \(imagesHost)")
    }
} catch {
    print(error)
}

stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:)

stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:) creates the Stack that reads published content from one environment of your stack.

NameTypeDescription
apiKey (required)String

API key of the stack.

Default: Not applicable
deliveryToken (required)String

Delivery token of the environment.

Default: Not applicable
environment (required)String

Environment that every request reads from.

Default: Not applicable
regionContentstackRegion

Region of the stack. Sets the delivery host.

Default: .us
hostString

Delivery host. Replaces the host of the region.

Default: Host.delivery
apiVersionString

API version in every request path.

Default: "v3"
branchString?

Branch UID that every request reads from.

Default: nil
configContentstackConfig

Decoding and network session settings.

Default: ContentstackConfig.default

Returns: Stack. A new stack for the given credentials and settings.

Validation

  • There is no client-side validation. The SDK accepts empty strings and does not check the credentials, the environment or the branch.
  • A wrong credential, environment or branch surfaces as an APIError from the first request of the stack, not from stack(...).

Behavior

  • Client-side only. stack(...) makes no request.
  • Every request of the stack goes to https://<host>/<apiVersion>/. It sends the API key in the api_key header, the delivery token in the access_token header and the environment in the environment query parameter.
  • The SDK selects the host as the sub-bullets below describe:
    • A host other than Host.delivery (cdn.contentstack.io) wins, and region then has no effect on the host. Give a bare host name, without https:// and without a path.
    • Otherwise the SDK reads the delivery host of region from the regions registry that the device has cached. When the device has no cached registry, it uses cdn.contentstack.io for .us and <region>-cdn.contentstack.com for other regions. The SDK never downloads the registry when it creates a stack.
    • The host property of the returned stack contains the result.
  • When branch is not nil, every request sends it in the branch header, which replaces a branch header that you set on config.sessionConfiguration.
  • Known issue: stacks that share one ContentstackConfig, including the default, share its session settings. A stack created without branch after one created with branch sends the earlier stack's branch header and reads content from that branch. Pass a new ContentstackConfig() as config to each stack that you create.
  • The SDK reads the config settings below once, when it creates the stack:
    • dateDecodingStrategy and timeZone set up the jsonDecoder of the stack.
    • sessionConfiguration and urlSessionDelegate create the network session of the stack. A later change to config does not reach a stack that already exists.
  • The ContentstackConfig page describes each setting.

Example

Basic usage: create a stack and fetch an entry

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
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)
            }
        }
    }

All parameters: a branch in the EU region with a custom host and config

import Foundation
import ContentstackSwift

var config = ContentstackConfig()
config.timeZone = TimeZone(identifier: "Europe/Berlin")

let stack = Contentstack.stack(apiKey: "API_KEY",
                               deliveryToken: "DELIVERY_TOKEN",
                               environment: "ENVIRONMENT",
                               region: .eu,
                               host: "eu-cdn.contentstack.com",
                               apiVersion: "v3",
                               branch: "BRANCH_UID",
                               config: config)
stack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID")
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        guard case .success(let entry) = result else { return }
        print("\(entry.title) from \(stack.host)")
    }

Two stacks on different branches: give each one its own config

import ContentstackSwift

// A new ContentstackConfig for each stack keeps the branch header of one stack out of the other.
let mainStack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT",
                                   config: ContentstackConfig())
let branchStack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT",
                                     branch: "BRANCH_UID", config: ContentstackConfig())

do {
    let mainEntry: EntryModel = try await mainStack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID").fetch()
    let branchEntry: EntryModel = try await branchStack.contentType(uid: "CONTENT_TYPE_UID").entry(uid: "ENTRY_UID").fetch()
    print(mainEntry.title, branchEntry.title)
} catch {
    print(error)
}