Stack

View as Markdown

Stack

Stack represents one environment of one Contentstack stack in the Swift Delivery SDK. Every other object you use comes from a stack. Use this class to

  • open content types, entries, assets, taxonomies and global fields
  • set the cache policy that new content type and asset queries start with
  • keep a local copy of your published content up to date with the Synchronization API

Stack has no public initializer, so Stack(...) does not compile. Create a stack with the stack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:) method of Contentstack.

Class-Level Properties

PropertyTypeAccessDefaultDescription
apiKeyStringRead-onlyConstructor argumentAPI key of the stack.
deliveryTokenStringRead-onlyConstructor argumentDelivery token of the environment.
environmentStringRead-onlyConstructor argumentEnvironment that every request reads from.
hostStringRead-onlycdn.contentstack.ioDelivery host that every request goes to.
regionContentstackRegionRead-only.usRegion that you passed when you created the stack.
apiVersionStringRead-only"v3"API version in every request path.
branchString?Read-onlynilBranch UID that every request sends.
cachePolicyCachePolicyRead/write.networkOnlyCache policy that new content type and asset queries start with.
jsonDecoderJSONDecoderRead-onlyThe SDK decoderDecoder that reads every response of the stack.

Class-Level Notes

Factory methods make no request.

Where cachePolicy applies.

  • The SDK copies cachePolicy into the query that contentType().query() or asset().query() creates, at the moment you create the query. A later change to the stack does not reach a query that already exists.
  • Entry, Asset, ContentType, GlobalField and Taxonomy objects, and the entry queries they create, start with .networkOnly and do not read the stack value. Set cachePolicy on those objects instead.
  • sync(_:syncTypes:then:) always goes to the network.

Sync. sync(_:syncTypes:then:) requests every page of a sync, following the pagination_token of each response. The method page lists the request that each SyncStack token sends, and the result that the completion handler receives for each page.

Capability Matrix

CapabilitySupportedNotes / Alternative
Sync more than one publish type, content type or locale in one initial syncNoThe SDK sends one value of each kind. Run one sync for each value, or sync without that filter.
Receive every page of a sync from the async formNoUse the completion-handler form of sync(_:syncTypes:then:).
Fetch one taxonomy by its UIDNotaxonomy(uid:) does not read the UID. Query entries by taxonomy term with taxonomy().query().

Method Index

The tables below group the methods by task.

Open content and assets. The methods below make no request.

Method NameReturnsDescription
contentType(uid:)A new content type object for the given UID.Opens a content type, to fetch its schema or its entries.
taxonomy(uid:)A new taxonomy object for this stack.Opens the taxonomies of the stack, to query entries by term.
asset(uid:)A new asset object for the given UID.Opens one asset, or all assets when you pass no UID.
globalField()A new global field object with no UID.Opens the list of global fields.
globalField(uid:)A new global field object for the given UID.Opens one global field.

Synchronize content. The method below always sends network requests.

Method NameReturnsDescription
sync(_:syncTypes:then:)Nothing. The completion handler receives the result.Syncs published content, or the changes since the last sync.

CachePolicy

CachePolicy sets where a fetch(_:) or find(_:) call gets its data. Set it on the cachePolicy property of the object before the call. Every object starts with .networkOnly.

The table below lists every case. CachePolicy has no raw values. The cache is the response cache of the SDK, with a capacity of 1 MB in memory and 5 MB on disk.

CaseMeaning
networkOnlySends a request. Stores a successful response in the cache. The default.
cacheOnlyReads the cache and sends no request. A cache miss returns SDKError.cacheError.
cacheElseNetworkReads the cache. Sends a request on a cache miss.
networkElseCacheSends a request. On a transport error or a status other than 200, returns the cached response when one exists, otherwise the error.
cacheThenNetworkReturns the cache result, then sends a request and returns the network result. The completion handler runs twice.

cacheThenNetwork details.

  • On a cache miss, the first call of the completion handler receives .failure(SDKError.cacheError) with ResponseType.cache. The second call receives the network result.
  • An async call returns one value, so the SDK serves cacheThenNetwork as cacheElseNetwork for async calls and logs the substitution at the error log level.

ResponseType

The completion handler of fetch(_:) and find(_:) receives a ResponseType that tells where the result came from. The table below lists its cases.

CaseMeaning
cacheThe result came from the cache of the SDK.
networkThe result came from a network request.

ResultsHandler

ResultsHandler<T> is the type of the completion handler of find(_:): (Result<T, Error>, ResponseType) -> Void. T is the response type you ask for, for example ContentstackResponse<EntryModel>.

Class-Level Snippet

The snippet below runs an initial sync, prints the item count of each page, and keeps the sync token of the last page for the next run.

Run an initial sync and keep the sync token

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.sync { (result: Result<SyncStack, Error>) in
    switch result {
    case .success(let syncStack):
        print("\(syncStack.items.count) items on this page")
        if !syncStack.syncToken.isEmpty {
            // The last page carries the sync token. Store it for the next sync.
            print("Sync token: \(syncStack.syncToken)")
        }
    case .failure(let error):
        if let apiError = error as? APIError {
            print("Error \(apiError.errorCode): \(apiError.errorMessage)")
        } else {
            print(error)
        }
    }
}

Methods

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

asset(uid:)

asset(uid:) returns an Asset object, which fetches one asset or queries all assets of the stack.

NameTypeDescription
uidString?

UID of the asset to open.

Default: nil

Returns: Asset. A new asset object for the given UID.

Validation

  • There is no client-side validation. The SDK does not check that the asset exists.
  • The SDK stops the app with a fatal error if you call fetch(_:) on an asset created without a UID, because the request path needs the UID.
  • Errors that do occur come from the fetch(_:) or find(_:) call that follows, not from asset(uid:).

Behavior

  • Client-side only. asset(uid:) makes no request.
  • The returned object supports one of the two uses below, depending on uid:
  • The returned object starts with cachePolicy .networkOnly. The query from its query() method starts with the cachePolicy of the stack.

Example

Basic usage: fetch one asset

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
    .fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
        switch result {
        case .success(let asset):
            print(asset.url)
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

List all assets without a UID

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
    .find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
        guard case .success(let assets) = result else { return }
        assets.items.forEach { print($0.title) }
    }

Use async/await

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let asset: AssetModel = try await stack.asset(uid: "ASSET_UID").fetch()
    print(asset.url)
} catch {
    print(error)
}

contentType(uid:)

contentType(uid:) returns a ContentType object, which fetches the schema of a content type, opens its entries, or queries all content types.

NameTypeDescription
uidString?

UID of the content type to open.

Default: nil

Returns: ContentType. A new content type object for the given UID.

Validation

  • There is no client-side validation. The SDK does not check that the content type exists.
  • The SDK stops the app with a fatal error if you call fetch(_:) or entry(uid:) without a UID, because both need it for the request path.
  • Errors that do occur come from the fetch(_:) or find(_:) call that follows, not from contentType(uid:).

Behavior

  • Client-side only. contentType(uid:) makes no request.
  • The returned object supports one of the two uses below, depending on uid:
  • The returned object starts with cachePolicy .networkOnly. The query from its query() method starts with the cachePolicy of the stack.

Example

Basic usage: fetch the schema of a content type

import ContentstackSwift

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

Open the entries of a content type

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        guard case .success(let entries) = result else { return }
        entries.items.forEach { print($0.title) }
    }

List all content types without a UID

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType().query()
    .find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
        guard case .success(let contentTypes) = result else { return }
        contentTypes.items.forEach { print($0.uid) }
    }

Use async/await

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let contentType: ContentTypeModel = try await stack.contentType(uid: "CONTENT_TYPE_UID").fetch()
    print(contentType.title)
} catch {
    print(error)
}

globalField()

globalField() returns a GlobalField object with no UID, which lists all global fields of the stack.

This method takes no parameters.

Returns: GlobalField. A new global field object with no UID.

Validation

  • There is no client-side validation.
  • The SDK stops the app with a fatal error if you call fetch(_:) on the returned object, because a single global field request needs a UID. Use find(_:), or open one global field with the globalField(uid:) method.
  • Errors that do occur come from the find(_:) call that follows, not from globalField().

Behavior

  • Client-side only. globalField() makes no request.
  • Call find(_:) on the returned object to list global fields, as in Get all global fields.
  • stack.globalField() calls this method, not globalField(uid:) with its default value. Both return an object with no UID.
  • The returned object starts with cachePolicy .networkOnly, whatever the cachePolicy of the stack.

Example

Basic usage: list all global fields

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.globalField()
    .find { (result: Result<ContentstackResponse<GlobalFieldModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let globalFields):
            globalFields.items.forEach { print($0.title) }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Use async/await

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let globalFields: ContentstackResponse<GlobalFieldModel> = try await stack.globalField().find()
    globalFields.items.forEach { print($0.title) }
} catch {
    print(error)
}

globalField(uid:)

globalField(uid:) returns a GlobalField object for one global field, which fetches its schema.

NameTypeDescription
uidString?

UID of the global field to open.

Default: nil

Returns: GlobalField. A new global field object for the given UID.

Validation

  • There is no client-side validation. The SDK does not check that the global field exists.
  • The SDK stops the app with a fatal error if you call fetch(_:) on a global field without a UID, because the request path needs the UID.
  • Errors that do occur come from the fetch(_:) or find(_:) call that follows, not from globalField(uid:).

Behavior

  • Client-side only. globalField(uid:) makes no request.
  • Call fetch(_:) on the returned object to get the global field, as in Get a single global field.
  • globalField(uid: nil) matches the globalField() method. Both return an object with no UID, which lists global fields with find(_:).
  • The returned object starts with cachePolicy .networkOnly, whatever the cachePolicy of the stack.

Example

Basic usage: fetch one global field

import ContentstackSwift

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

Use async/await

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let globalField: GlobalFieldModel = try await stack.globalField(uid: "GLOBAL_FIELD_UID").fetch()
    print(globalField.title)
} catch {
    print(error)
}

sync(_:syncTypes:then:)

sync(_:syncTypes:then:) fetches the published content of the environment, or the changes since your last sync, to keep a local copy up to date.

func sync(_ syncStack: SyncStack = SyncStack(), syncTypes: [SyncStack.SyncableTypes] = [.all]) async throws -> SyncStack is the async form, with the same parameters except the completion handler.

NameTypeDescription
syncStackSyncStack

Token state that selects the kind of sync.

Default: SyncStack()
syncTypes[SyncStack.SyncableTypes]

Filters for an initial sync.

Default: [.all]
completion (required)@escaping (Result<SyncStack, Error>) -> Void

Receives each page of the result, or the error.

Default: Not applicable

Returns: Void. Nothing. The completion handler receives the result.

The async form returns the last page of the sync and throws on failure.

Validation

  • There is no client-side validation. The SDK sends the tokens and filters as given.
  • When the API rejects the request, the result is .failure with an APIError (the async form throws it). Read errorCode, errorMessage and statusCode from it. An expired or unknown sync token surfaces this way.
  • A response that holds neither a sync_token nor a pagination_token, or both, fails with SDKError.syncError.

Additional Resource Refer to Delivery API Errors for the full error code list.

Behavior

  • The tokens of syncStack select the request:
    • A new SyncStack(), with no token, sends an Initial Sync request with init=true. Use it once, when the app has no content yet.
    • SyncStack(syncToken:) sends a Subsequent Sync request, which returns the content published, unpublished or deleted since the sync that gave you the token.
    • SyncStack(paginationToken:) sends a Sync using pagination token request, which continues a sync from that page.
  • The SDK applies syncTypes only to an initial sync. With a token, it drops them.
  • Each syncTypes value adds one query parameter, and each kind takes one value, as the SyncableTypes section of the SyncStack page describes. The API returns the content that matches all of them. Run one sync for each value of the same kind that you need.
  • The API returns up to 100 records for each request. While a response carries a pagination_token, the SDK requests the next page itself.
  • The completion handler runs once for each page, as described below:
    • Each call receives a new SyncStack whose items contain that page only. Copy the items you need.
    • On every page except the last, paginationToken contains a token and syncToken is empty. On the last page, syncToken contains the token and paginationToken is empty.
    • Store the syncToken of the last page, and pass it as SyncStack(syncToken:) on the next run.
  • When a page fails, the completion handler receives .failure and the SDK requests no more pages. To continue, pass the paginationToken of the last page that succeeded as SyncStack(paginationToken:).
  • Sync requests always go to the network. They do not read the cachePolicy of the stack. Each request sends the environment of the stack.
  • Known issue: the async form requests every page but returns only the last one, so the items of earlier pages are lost while totalCount still counts them. Use the completion-handler form when a sync can return more than 100 items.

Example

Basic usage: run an initial sync and keep the sync token

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
var syncedItems: [Any] = []
stack.sync { (result: Result<SyncStack, Error>) in
    switch result {
    case .success(let syncStack):
        // items holds this page only, so copy them before the next page arrives.
        syncedItems.append(contentsOf: syncStack.items)
        if !syncStack.syncToken.isEmpty {
            // The last page carries the sync token. Store it for the next sync.
            print("\(syncedItems.count) items. Sync token: \(syncStack.syncToken)")
        }
    case .failure(let error):
        if let apiError = error as? APIError {
            print("Error \(apiError.errorCode): \(apiError.errorMessage)")
        } else {
            print(error)
        }
    }
}

All parameters: an initial sync filtered by content type, locale, date and publish type

import Foundation
import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let lastWeek = Date().addingTimeInterval(-7 * 24 * 60 * 60)
stack.sync(SyncStack(),
           syncTypes: [.contentType("CONTENT_TYPE_UID"), .locale("en-us"), .startFrom(lastWeek), .publishType(.entryPublished)],
           then: { (result: Result<SyncStack, Error>) in
    guard case .success(let syncStack) = result else { return }
    print("\(syncStack.items.count) items on this page")
})

Subsequent sync: get the changes since the last sync

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.sync(SyncStack(syncToken: "SYNC_TOKEN")) { (result: Result<SyncStack, Error>) in
    guard case .success(let syncStack) = result else { return }
    print("\(syncStack.items.count) changes on this page")
    if !syncStack.syncToken.isEmpty {
        print("Next sync token: \(syncStack.syncToken)")
    }
}

Resume a sync from a pagination token

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.sync(SyncStack(paginationToken: "PAGINATION_TOKEN")) { (result: Result<SyncStack, Error>) in
    guard case .success(let syncStack) = result else { return }
    print("\(syncStack.items.count) items on this page")
}

Use async/await: a subsequent sync with few changes

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    // The async form returns only the last page. Use it when the changes fit in one page of 100 items.
    let syncStack = try await stack.sync(SyncStack(syncToken: "SYNC_TOKEN"))
    print("\(syncStack.items.count) of \(syncStack.totalCount) items. Next sync token: \(syncStack.syncToken)")
} catch {
    print(error)
}

taxonomy(uid:)

taxonomy(uid:) returns a Taxonomy object, which queries the entries of the stack by taxonomy term.

NameTypeDescription
uidString?

Has no effect. The SDK does not read it.

Default: nil

Returns: Taxonomy. A new taxonomy object for this stack.

Validation

  • There is no client-side validation.
  • Errors that do occur come from the find(_:) or fetch(_:) call that follows, not from taxonomy(uid:).

Behavior

  • Client-side only. taxonomy(uid:) makes no request.
  • The SDK does not store uid and does not send it in any request, so taxonomy(uid: "TAXONOMY_UID") returns the same object as taxonomy().
  • The returned object sends Get all entries with defined taxonomies requests. Name the taxonomy in the query condition instead, for example taxonomies.TAXONOMY_UID.
  • The returned object starts with cachePolicy .networkOnly, whatever the cachePolicy of the stack.

Example

Basic usage: find the entries tagged with a taxonomy term

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.taxonomy().query()
    .where(valueAtKey: "taxonomies.TAXONOMY_UID", .equals("TERM_UID"))
    .find { (result: Result<ContentstackResponse<TaxonomyModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let entries):
            entries.items.forEach { print($0.title) }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Use async/await

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let entries: ContentstackResponse<TaxonomyModel> = try await stack.taxonomy().query()
        .where(valueAtKey: "taxonomies.TAXONOMY_UID", .equals("TERM_UID"))
        .find()
    entries.items.forEach { print($0.title) }
} catch {
    print(error)
}