Contentstack Delivery Swift SDK
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.
| Class | Role | Accessed via |
|---|---|---|
| Contentstack | Entry point that creates a stack, looks up region endpoints and renders rich text. | Contentstack.stack(apiKey:deliveryToken:environment:) |
| ContentstackConfig | Session, date decoding, TLS delegate and early access settings for a stack. | ContentstackConfig() |
| Stack | One stack and one environment, and the factory for every other object. | Contentstack.stack(...) |
| ContentstackLogger | Log level and log destination for the whole SDK. | ContentstackLogger.logLevel |
Entries and queries. The table below lists the types that read entries.
| Class | Role | Accessed via |
|---|---|---|
| ContentType | One content type, its schema, and the factory for its entries. | stack.contentType(uid:) |
| Entry | One entry of a content type, and the EntryModel it decodes into. | contentType.entry(uid:) |
| EntryQueryable | Locale, field projection, references and variants for entries and entry queries. | Methods on Entry and Query |
| Query | Filters, sorts and pages the entries of a content type or a taxonomy search. | contentType.entry().query() |
| QueryOn | A query that decodes entries into your own model type. | contentType.entry().query(MyModel.self) |
| BaseQuery | The find, limit, skip, sort and raw-parameter methods every query shares. | Methods on every query |
| ContentstackResponse | The items and counts of one find response. | find(_:) result |
| Taxonomy | Searches entries by taxonomy terms. | stack.taxonomy() |
| Global Fields | One global field or the list of global fields. | stack.globalField(uid:) |
| SystemFields | The 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.
| Class | Role | Accessed via |
|---|---|---|
| Asset | One asset, and the AssetModel it decodes into. | stack.asset(uid:) |
| AssetQuery | Filters and lists assets. | stack.asset().query() |
| ContentTypeQuery | Filters and lists content types. | stack.contentType().query() |
| ImageTransform | Builds 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.
| Class | Role | Accessed via |
|---|---|---|
| SyncStack | The result of one sync request, with its items and tokens. | sync(_:syncTypes:then:) result |
| APIError | The API rejection and the SDK's own error cases. | .failure of a Result, or a thrown error |
Task Index
| Task | Start here | Class |
|---|---|---|
| Fetch one entry by UID | fetch(_:) | Entry |
| Include referenced entries | includeReference(with:) | EntryQueryable |
| Filter entries by a field value | where(valueAtKey:_:) | Query |
| Page through a large result | limit(to:) | BaseQuery |
| Get entries in another locale | locale(_:) | EntryQueryable |
| Fetch an entry variant | variants(uid:) | EntryQueryable |
| Find entries tagged with a taxonomy term | query() | Taxonomy |
| List assets | find(_:) | BaseQuery |
| Resize or reformat an image | url(with:) | ImageTransform |
| Fetch a global field schema | fetch(_:) | Global Fields |
| Sync all published content, then only changes | sync(_:syncTypes:then:) | Stack |
| Target a region or branch | stack(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
| Concern | Behavior | Default when unset |
|---|---|---|
| Authentication | The 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 endpoints | Pass region to Contentstack.stack to target another region. A host you pass yourself always wins. | .us, host cdn.contentstack.io. |
| Branches | Pass 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 retry | The SDK sends each request once and does not retry. Handle 429 in your own code. | No retry. |
| Timeouts | The SDK sets no timeout of its own. Set one on sessionConfiguration of a ContentstackConfig. | The system default of URLSessionConfiguration.default. |
| Errors | When 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 UID | fetch(_:) 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. |
| Caching | Set 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
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Automatic retry on rate limits | No | Retry 429 responses in your own code, with a delay between attempts. |
| Early access features through setEarlyAccess(_:) | No | Add the x-header-ea header to sessionConfiguration.httpAdditionalHeaders of your ContentstackConfig. |
| Two stacks with different branches on one ContentstackConfig | No | Create a separate ContentstackConfig for each stack. |