Contentstack Delivery Swift SDK

View as Markdown

Overview

This reference covers the public API of the ContentstackSwift package, the Swift Content Delivery SDK, one page per class. Use it to look up parameters, return types, validation behavior, and Swift examples for every method you reach from import ContentstackSwift.

Before you begin This reference assumes you have installed and initialized the SDK. If you have not, complete the Get Started with Swift SDK guide first. This SDK requires Swift 5.6 or later and iOS 13, macOS 10.15, tvOS 13 or watchOS 6 or later. This reference documents version 2.5.1, and the changelog lists behavior changes between releases.

Note The latest ContentstackSwift pod on CocoaPods is version 2.5.0, so pod users do not get the fixes in 2.5.1. CocoaPods is no longer the recommended route for new projects. Add the SDK with Swift Package Manager.

Minimum Working Example

The snippet below creates a stack, fetches one entry, and prints its title or the error the API returned.

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)
            }
        }
    }

SDK Structure

Every object that reads content comes from a Stack. Factory methods such as contentType(uid:), entry(uid:), asset(uid:) and query() make no request. Setter methods such as locale(_:), limit(to:) or where(valueAtKey:_:) store the setting and return the same object, so you can chain them. A send method makes the request: fetch(_:) for one entry, asset, content type or global field, find(_:) for a query, and sync(_:syncTypes:then:) on Stack.

  • Two call styles. Every send method has a completion-handler form and an async throws form with the same name. The completion handler receives a Result and a ResponseType. The async form returns the value and throws on failure.
  • Typed results. fetch and find are generic, so specify the model type in the closure or the variable annotation, for example Result<EntryModel, Error> or let entry: EntryModel. Without it the code does not compile.
  • Where errors surface. Setters check nothing. A value the API rejects comes back from the next fetch(_:) or find(_:) call, not from the setter.

Class Overview

Start and configure. The table below lists the types that create a stack and configure its requests.

ClassRoleAccessed via
ContentstackEntry point that creates a stack, looks up region endpoints and renders rich text.Contentstack.stack(apiKey:deliveryToken:environment:)
ContentstackConfigSession, date decoding, TLS delegate and early access settings for a stack.ContentstackConfig()
StackOne stack and one environment, and the factory for every other object.Contentstack.stack(...)
ContentstackLoggerLog level and log destination for the whole SDK.ContentstackLogger.logLevel

Entries and queries. The table below lists the types that read entries.

ClassRoleAccessed via
ContentTypeOne content type, its schema, and the factory for its entries.stack.contentType(uid:)
EntryOne entry of a content type, and the EntryModel it decodes into.contentType.entry(uid:)
EntryQueryableLocale, field projection, references and variants for entries and entry queries.Methods on Entry and Query
QueryFilters, sorts and pages the entries of a content type or a taxonomy search.contentType.entry().query()
QueryOnA query that decodes entries into your own model type.contentType.entry().query(MyModel.self)
BaseQueryThe find, limit, skip, sort and raw-parameter methods every query shares.Methods on every query
ContentstackResponseThe items and counts of one find response.find(_:) result
TaxonomySearches entries by taxonomy terms.stack.taxonomy()
Global FieldsOne global field or the list of global fields.stack.globalField(uid:)
SystemFieldsThe system fields every entry, asset and global field model carries.Properties of a model

Assets and images. The table below lists the types that read assets and build image URLs.

ClassRoleAccessed via
AssetOne asset, and the AssetModel it decodes into.stack.asset(uid:)
AssetQueryFilters and lists assets.stack.asset().query()
ContentTypeQueryFilters and lists content types.stack.contentType().query()
ImageTransformBuilds an Image Delivery API URL that resizes, crops or reformats an image.ImageTransform()

Sync and errors. The table below lists the sync result and the error types.

ClassRoleAccessed via
SyncStackThe result of one sync request, with its items and tokens.sync(_:syncTypes:then:) result
APIErrorThe API rejection and the SDK's own error cases..failure of a Result, or a thrown error

Task Index

TaskStart hereClass
Fetch one entry by UIDfetch(_:)Entry
Include referenced entriesincludeReference(with:)EntryQueryable
Filter entries by a field valuewhere(valueAtKey:_:)Query
Page through a large resultlimit(to:)BaseQuery
Get entries in another localelocale(_:)EntryQueryable
Fetch an entry variantvariants(uid:)EntryQueryable
Find entries tagged with a taxonomy termquery()Taxonomy
List assetsfind(_:)BaseQuery
Resize or reformat an imageurl(with:)ImageTransform
Fetch a global field schemafetch(_:)Global Fields
Sync all published content, then only changessync(_:syncTypes:then:)Stack
Target a region or branchstack(apiKey:deliveryToken:environment:region:host:apiVersion:branch:config:)Contentstack

Key Usage Patterns

These examples assume a stack created as in the Minimum Working Example.

Resolve entry references

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "blog_post").entry(uid: "ENTRY_UID")
    .includeReference(with: ["author"])
    .fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
        guard case .success(let entry) = result else { return }
        print(entry.fields?["author"] ?? "")
    }

Filter and page entries

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let response: ContentstackResponse<EntryModel> = try await stack.contentType(uid: "blog_post").entry().query()
        .where(valueAtKey: "category", .equals("news"))
        .orderByDecending(keyPath: "updated_at")
        .limit(to: 20)
        .skip(theFirst: 20)
        .find()
    for entry in response.items {
        print(entry.title)
    }
} catch {
    print(error)
}

Sync, then fetch changes

import ContentstackSwift

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

SDK-Wide Notes

ConcernBehaviorDefault when unset
AuthenticationThe stack sends the API key and delivery token as the api_key and access_token headers of every request, and the environment as a query parameter. The SDK checks none of the three before the first request.Not applicable, Contentstack.stack takes all three.
Regions and endpointsPass region to Contentstack.stack to target another region. A host you pass yourself always wins..us, host cdn.contentstack.io.
BranchesPass branch to Contentstack.stack. Every request of the stack then sends the branch header.No header, so the API uses the main branch.
Rate limiting and retryThe SDK sends each request once and does not retry. Handle 429 in your own code.No retry.
TimeoutsThe SDK sets no timeout of its own. Set one on sessionConfiguration of a ContentstackConfig.The system default of URLSessionConfiguration.default.
ErrorsWhen the API rejects a request, the result is .failure with an APIError that holds errorCode, errorMessage and statusCode. The async form throws the same error. A connection failure is a URLError.Not applicable.
Missing UIDfetch(_:) on an entry, asset, content type or global field created without a UID stops the app with a fatal error, because a single-item fetch needs a UID.Not applicable.
CachingSet cachePolicy on each entry, query, asset, content type or global field. A stack's cachePolicy reaches only content type and asset queries. cacheThenNetwork calls the completion handler twice, and the async forms read it as cacheElseNetwork..networkOnly.

Warning This SDK requires a delivery token. A management token or a preview token returns error code 109, "We can't find that Stack", which does not report that the token type is wrong. Create a delivery token under Settings, Tokens in your stack.

SDK Limitations

CapabilitySupportedNotes / Alternative
Automatic retry on rate limitsNoRetry 429 responses in your own code, with a delay between attempts.
Early access features through setEarlyAccess(_:)NoAdd the x-header-ea header to sessionConfiguration.httpAdditionalHeaders of your ContentstackConfig.
Two stacks with different branches on one ContentstackConfigNoCreate a separate ContentstackConfig for each stack.