BaseQuery

View as Markdown

BaseQuery

BaseQuery is the protocol that gives every query type its shared methods. Use these methods to

  • filter by field value with where(valueAtKeyPath:_:) or raw conditions
  • sort and read one page at a time
  • add a URL parameter or HTTP header the SDK has no method for
  • send the request with find(_:)

Query, QueryOn, AssetQuery and ContentTypeQuery adopt BaseQuery. This page documents each method once, and each method works the same way on all four types.

Instance State

BaseQuery is a protocol, so you never create one. A factory returns an object that adopts it. A model type that does not match the factory sends the request to the wrong endpoint. Pass find(_:) the model type that the following table gives for each factory:

FactoryQuery typeModel type for find(_:)
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()QueryEntryModel, or your own EntryDecodable type
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query(Product.self)QueryOn<Product>Product
stack.taxonomy().query()QueryTaxonomyModel
stack.asset().query()AssetQueryAssetModel, or your own AssetDecodable type
stack.contentType().query()ContentTypeQueryContentTypeModel
  • The model type selects the endpoint. A different model type compiles, and the request goes to the endpoint of that model with the parameters of the query.
  • find(_:) with EntryModel on a query from stack.taxonomy().query() stops the app, because the entries path needs a content type UID and that query has none.

Class-Level Notes

Where each method writes.

Return values.

  • Every setter returns Self, the type you called it on, so a chain keeps the methods of Query, AssetQuery or ContentTypeQuery.
  • skip(theFirst:), limit(to:) and the two sort methods carry the @discardableResult attribute. The other setters lack it, so a call whose result goes unused compiles with a warning. Chain those calls or assign the result.

Settings stay on the query.

  • find(_:) does not clear the query, so a second find(_:) sends the same request again.

Class-Level Properties

The following table lists the property requirements that BaseQuery inherits from the QueryProtocol protocol. Each adopting class declares them, so the defaults belong to that class.

PropertyTypeAccessDefaultDescription
ResourceTypeAssociated typeRead onlyEntryModel on Query, AssetModel on AssetQuery, ContentTypeModel on ContentTypeQueryModel type the class declares. find(_:) takes its model type from the caller instead.
stackStackRead and writeThe stack that created the queryStack that sends the request.
parameters[String: Any]Read and writeSet by the adopting classURL parameters the request carries.
queryParameter[String: Any]Read and write[:]Conditions that find(_:) sends as JSON in query.
headers[String: String]Read and write[:]HTTP headers the request carries.
cachePolicyCachePolicyRead and writeSet by the adopting classWhether find(_:) reads the network or the cache. See Stack.

QueryProtocol

QueryProtocol is the base of BaseQuery and of EntryQueryable. It requires the six members in the Class-Level Properties table above and adopts CachePolicyAccessible. It declares no methods.

Queryable

Queryable requires a find method for a collection. Its two requirements are find<ResourceType>(_ completion: @escaping ResultsHandler<ContentstackResponse<ResourceType>>) and find<ResourceType>() async throws -> ContentstackResponse<ResourceType>.

  • GlobalField is the only type that adopts Queryable. The query types get their find(_:) from BaseQuery instead.

ResourceQueryable

ResourceQueryable requires a fetch method for one item. Its two requirements are fetch<ResourceType>(_ completion: @escaping ResultsHandler<ResourceType>) and fetch<ResourceType>() async throws -> ResourceType.

FieldKeysQueryable

FieldKeysQueryable requires one associated type, FieldKeys, which must conform to CodingKey. The cases of FieldKeys identify the fields of a model.

  • EntryDecodable, AssetDecodable and GlobalFieldDecodable inherit FieldKeysQueryable, so every model type you decode adopts it.
  • QueryOn reads FieldKeys from your model, so its where(queryableCodingKey:_:) and sort methods accept the cases of your own enum.

Method Index

Every method below works on Query, QueryOn, AssetQuery and ContentTypeQuery. The tables below group the methods by task.

Filter the results. Available on any query, before find(_:).

Method NameReturnsDescription
where(valueAtKeyPath:_:)The same query, for chaining.Matches items by a field path and an operation.
addQuery(with:value:)The same query, for chaining.Adds one raw condition to the query parameter.
addQuery(dictionary:)The same query, for chaining.Adds several raw conditions to the query parameter.

Sort and paginate. Available on any query, before find(_:).

Method NameReturnsDescription
orderByAscending(keyPath:)The same query, for chaining.Sorts items by a field in ascending order.
orderByDecending(keyPath:)The same query, for chaining.Sorts items by a field in descending order.
limit(to:)The same query, for chaining.Sets the maximum number of items returned.
skip(theFirst:)The same query, for chaining.Skips a number of items before the page starts.

Send a parameter or header the SDK has no method for. Available on any query, before find(_:).

Method NameReturnsDescription
addURIParam(with:value:)The same query, for chaining.Adds one URL parameter.
addURIParam(dictionary:)The same query, for chaining.Adds several URL parameters.
addValue(_:forHTTPHeaderField:)The same query, for chaining.Adds one HTTP header to the request.

Send the request. Available on any query, as the last call in the chain.

Method NameReturnsDescription
find(_:)Nothing. The completion handler receives the result.Sends the query and returns one page of items.

Class-Level Snippet

The snippet below reads the second page of twenty PNG assets, newest first, with the total count.

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
    .where(valueAtKeyPath: "content_type", .equals("image/png"))
    .orderByDecending(keyPath: "created_at")
    .skip(theFirst: 20)
    .limit(to: 20)
    .include(params: .count)
    .find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            print("Total assets: \(contentstackResponse.count ?? 0)")
            for asset in contentstackResponse.items {
                print(asset.title, asset.url)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Methods

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

addQuery(dictionary:)

addQuery(dictionary:) adds several raw conditions to the query parameter in one call.

NameTypeDescription
dictionary (required)[String: Any]

Field UIDs or operators and their condition values.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • There is no client-side validation when you call addQuery(dictionary:). An empty dictionary adds nothing.
  • The next find(_:) stops the app with NSInvalidArgumentException if a value holds a non-JSON type such as Date, because JSONSerialization cannot convert it.
  • Errors that the API returns come from the find(_:) call that follows, not from addQuery(dictionary:).

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

Behavior

  • Client-side only. addQuery(dictionary:) calls the addQuery(with:value:) method once per pair, so the rules on that page apply to each pair. It makes no request.
  • The method adds to the conditions the query already holds. A name the query already holds takes the new value.
  • The method lacks the @discardableResult attribute. Chain the call or assign the result to avoid an unused-result warning.

Example

Basic usage: add a reference search and a price limit

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .addQuery(dictionary: [
        "brand": ["$in_query": ["title": "Apple Inc."]],
        "price_in_usd": ["$lt": 600]
    ])
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

addQuery(with:value:)

addQuery(with:value:) adds one raw condition to the query parameter, for an operator that the where methods cannot express.

NameTypeDescription
with (required)String

Field UID, dot path or operator such as $or.

Default: Not applicable
value (required)Any

Condition value, as a JSON-compatible Swift value.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • There is no client-side validation when you call addQuery(with:value:).
  • The next find(_:) stops the app with NSInvalidArgumentException if value holds a non-JSON type such as Date, because JSONSerialization cannot convert it. Use String, Int, Double, Bool, arrays and [String: Any] dictionaries of those types.
  • Errors that the API returns come from the find(_:) call that follows, not from addQuery(with:value:).

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

Behavior

  • Client-side only. addQuery(with:value:) writes the pair into the queryParameter dictionary, the same store that the where methods use, and makes no request. The find(_:) method sends the whole dictionary as JSON in the query parameter.
  • A condition on a name that the query already holds replaces it, including one from a where method.
  • A nested dictionary becomes a nested JSON object. Use it for an operator the SDK has no case for, such as $in_query for a reference search or levels on a taxonomy operator. See Reference Search Equals and Equal and Below Operator.
  • The method lacks the @discardableResult attribute. Chain the call or assign the result to avoid an unused-result warning.

Example

Basic usage: search entries by a referenced field

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .addQuery(with: "brand", value: ["$in_query": ["title": "Apple Inc."]])
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Match taxonomy terms down to two levels

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.taxonomy().query()
    .addQuery(with: "taxonomies.color", value: ["$eq_below": "blue", "levels": 2])
    .find { (result: Result<ContentstackResponse<TaxonomyModel>, Error>, response: ResponseType) in
        guard case .success(let contentstackResponse) = result else { return }
        for entry in contentstackResponse.items {
            print(entry.title)
        }
    }

Join asset conditions with $or

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
    .addQuery(with: "$or", value: [["filename": "logo.png"], ["filename": "banner.png"]])
    .find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
        guard case .success(let contentstackResponse) = result else { return }
        for asset in contentstackResponse.items {
            print(asset.fileName, asset.url)
        }
    }

addURIParam(dictionary:)

addURIParam(dictionary:) adds several URL parameters to the request, for parameters the SDK has no method for.

NameTypeDescription
dictionary (required)[String: String]

Parameter names and values to add.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • There is no client-side validation. An empty dictionary adds nothing.
  • Errors that do occur come from the find(_:) call that follows, not from addURIParam(dictionary:).

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

Behavior

  • Client-side only. addURIParam(dictionary:) calls the addURIParam(with:value:) method once per pair, so the rules on that page apply to each pair. It makes no request.
  • The method adds to the parameters the query already holds. It does not remove any, and a name the query already holds takes the new value.
  • The method lacks the @discardableResult attribute. Chain the call or assign the result to avoid an unused-result warning.

Example

Basic usage: add two parameters at once

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .addURIParam(dictionary: ["include_branch": "true", "include_taxonomy_terms": "true"])
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

addURIParam(with:value:)

addURIParam(with:value:) adds one URL parameter to the request, for a parameter the SDK has no method for.

NameTypeDescription
with (required)String

Name of the URL parameter.

Default: Not applicable
value (required)String

Value of the URL parameter.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • There is no client-side validation. The SDK does not check the name against the parameters the API accepts.
  • Errors that do occur come from the find(_:) call that follows, not from addURIParam(with:value:).

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

Behavior

  • Client-side only. addURIParam(with:value:) writes the pair into the parameters dictionary and makes no request. The find(_:) method sends it as name=value.
  • A value for a name that the query already holds replaces it, including a value from a method such as limit(to:).
  • The SDK percent-encodes the value but leaves & as is. A & in the value ends the parameter early, so the API receives only the text before it.
  • Three names have a fixed meaning for the SDK:
    • content_type and uid build the request path, and the SDK does not send them as parameters.
    • query carries the conditions. When the query holds any, find(_:) writes them over this name.
  • The method lacks the @discardableResult attribute. Chain the call or assign the result to avoid an unused-result warning.

Example

Basic usage: add the branch key to each entry

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .addURIParam(with: "include_branch", value: "true")
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title, entry.fields?["_branch"] ?? "")
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Resolve taxonomy term names in the response

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .addURIParam(with: "include_taxonomy_terms", value: "true")
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        guard case .success(let contentstackResponse) = result else { return }
        for entry in contentstackResponse.items {
            print(entry.title, entry.fields?["taxonomies"] ?? "")
        }
    }

addValue(_:forHTTPHeaderField:)

addValue(_:forHTTPHeaderField:) adds one HTTP header to the request that the query sends.

NameTypeDescription
value (required)String

Value of the header.

Default: Not applicable
forHTTPHeaderField (required)String

Name of the header.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • There is no client-side validation. The SDK does not check the header name.
  • Errors that do occur come from the find(_:) call that follows, not from addValue(_:forHTTPHeaderField:).

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

Behavior

  • Client-side only. addValue(_:forHTTPHeaderField:) writes the pair into the headers dictionary of the query and makes no request. The find(_:) method adds each header to the request.
  • A second call with the same header name replaces the first value.
  • The header applies to this query only. Other queries, entries and assets from the same stack do not carry it.
  • A header on the request takes precedence over a session header with the same name. For example, it overrides the branch header that Contentstack.stack(...) sets from its branch argument.
  • An api_key or access_token header set here gives the request two values for that header, because the SDK sets both on every request. Leave these two headers out.
  • The method lacks the @discardableResult attribute. Chain the call or assign the result to avoid an unused-result warning.

Example

Basic usage: read entries from another branch

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .addValue("BRANCH_UID", forHTTPHeaderField: "branch")
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

find(_:)

find(_:) sends the query and passes one page of matching items to the completion handler.

It has two forms with the same name:

  • Completion handler form: find<ResourceType>(_ completion: @escaping ResultsHandler<ContentstackResponse<ResourceType>>)
  • async form: find<ResourceType>() async throws -> ContentstackResponse<ResourceType>
NameTypeDescription
completion (required)@escaping (Result<ContentstackResponse<ResourceType>, Error>, ResponseType) -> Void

Receives the result and where it came from.

Default: Not applicable

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

The async form returns the matching items and throws on failure.

Validation

  • There is no client-side validation.
  • 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.
  • A transport failure, such as no network or a timeout, arrives as the URLError from URLSession. A response that does not decode into the model type arrives as a DecodingError. A cache miss under .cacheOnly arrives as SDKError.cacheError.
  • The SDK stops the app if you pass an EntryDecodable type such as EntryModel on a taxonomy query, because the entries path needs a content type UID. Use TaxonomyModel there.
  • The SDK stops the app with NSInvalidArgumentException if a condition holds a non-JSON value, because JSONSerialization cannot convert it. Examples are a Date inside .includes or in addQuery(with:value:). Pass dates as ISO 8601 strings.

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

Behavior

  • Each call sends one GET request. The model type you name in the completion handler or the variable annotation selects the request path, as the following table shows:
Model typeRequest path
EntryModel or another EntryDecodable type/content_types/{content_type_uid}/entries. See Get all entries.
TaxonomyModel/taxonomies/entries. See Get all entries with defined taxonomies.
AssetModel or another AssetDecodable type/assets. See Get all assets.
ContentTypeModel/content_types. See Get all content types.
  • When the query holds conditions, find(_:) converts them to JSON and sends them in the query parameter. Every entry in parameters goes out as its own URL parameter, and the SDK adds the environment of the stack.
  • On success, the result is a ContentstackResponse. items holds the page of models. count holds the total only when the query asked for it, for example with include(params: .count).
  • find(_:) returns one page. Without limit(to:), the API returns the first 100 entries or assets. Use skip(theFirst:) and limit(to:) to read later pages. See Pagination.
  • The query keeps its settings, so a second find(_:) on the same query sends the same request again.
  • The cachePolicy of the query picks the network or the cache, and the ResponseType argument says which one answered. Under .cacheThenNetwork, the completion handler runs twice, once for the cache and once for the network. The async form serves .cacheThenNetwork as .cacheElseNetwork. See Stack.

Example

Basic usage: list 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
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.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 response: ContentstackResponse<EntryModel> = try await stack.contentType(uid: "CONTENT_TYPE_UID").entry().query().find()
    for entry in response.items {
        print(entry.title)
    }
} catch {
    print(error)
}

List assets and content types

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 contentstackResponse) = result else { return }
        for asset in contentstackResponse.items {
            print(asset.fileName, asset.url)
        }
    }
stack.contentType().query()
    .find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
        guard case .success(let contentstackResponse) = result else { return }
        for contentType in contentstackResponse.items {
            print(contentType.uid, contentType.title)
        }
    }

List entries by taxonomy term

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.taxonomy().query()
    .where(valueAtKey: "taxonomies.color", .equals("red"))
    .find { (result: Result<ContentstackResponse<TaxonomyModel>, Error>, response: ResponseType) in
        guard case .success(let contentstackResponse) = result else { return }
        for entry in contentstackResponse.items {
            print(entry.title)
        }
    }

Read every page of entries

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let pageSize: UInt = 100
var skip: UInt = 0
var titles: [String] = []
do {
    while true {
        let page: ContentstackResponse<EntryModel> = try await stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
            .include(params: .count)
            .skip(theFirst: skip)
            .limit(to: pageSize)
            .find()
        titles += page.items.map { $0.title }
        skip += pageSize
        if page.items.isEmpty || skip >= (page.count ?? 0) { break }
    }
    print("Read \(titles.count) entries")
} catch {
    print(error)
}

limit(to:)

limit(to:) sets the maximum number of items that the response returns.

NameTypeDescription
to (required)UInt

Maximum number of items to return.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • The SDK lowers a value above 1000 to 1000 before it sends the request. There is no other client-side validation.
  • The type is UInt, so a negative number does not compile.
  • The API accepts positive integers only. For 0, it returns the default number of records rather than every record. See Limit.
  • Errors that do occur come from the find(_:) call that follows, not from limit(to:).

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

Behavior

  • Client-side only. limit(to:) writes the limit URL parameter and makes no request. The find(_:) method sends it.
  • Without limit(to:), the API returns the first 100 entries or assets. See Pagination.
  • A second call replaces the first value.
  • Use it with skip(theFirst:) to read one page at a time.
  • The method carries the @discardableResult attribute, so a call on a separate line compiles without a warning.

Example

Basic usage: read at most five entries

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .limit(to: 5)
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Read the first ten assets

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let query = stack.asset().query()
query.limit(to: 10)
query.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
    guard case .success(let contentstackResponse) = result else { return }
    for asset in contentstackResponse.items {
        print(asset.fileName)
    }
}

orderByAscending(keyPath:)

orderByAscending(keyPath:) sorts the items in ascending order of one field.

NameTypeDescription
keyPath (required)String

UID or dot path of the field to sort by.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • There is no client-side validation. The SDK does not check that the field exists.
  • Errors that do occur come from the find(_:) call that follows, not from orderByAscending(keyPath:).

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

Behavior

  • Client-side only. orderByAscending(keyPath:) writes the field to the asc URL parameter and makes no request. The find(_:) method sends it. See Order by asc.
  • A second call replaces the field from the first.
  • The orderByDecending(keyPath:) method writes a separate parameter, so calling both sends both.
  • To sort by a field inside a Group field, pass its dot path, for example bank_offers.discount_in_percentage. See Order by asc Operator Within Group.
  • On a query from stack.taxonomy().query(), the API sorts only on title, created_at, updated_at, published_at and url. See the Taxonomy section of Queries.
  • The method carries the @discardableResult attribute, so a call on a separate line compiles without a warning.

Example

Basic usage: sort entries by price

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .orderByAscending(keyPath: "price_in_usd")
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Sort assets by update date

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
    .orderByAscending(keyPath: "updated_at")
    .find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
        guard case .success(let contentstackResponse) = result else { return }
        for asset in contentstackResponse.items {
            print(asset.fileName)
        }
    }

orderByDecending(keyPath:)

orderByDecending(keyPath:) sorts the items in descending order of one field.

NameTypeDescription
keyPath (required)String

UID or dot path of the field to sort by.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • There is no client-side validation. The SDK does not check that the field exists.
  • Errors that do occur come from the find(_:) call that follows, not from orderByDecending(keyPath:).

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

Behavior

  • Client-side only. orderByDecending(keyPath:) writes the field to the desc URL parameter and makes no request. The find(_:) method sends it. See Order by desc.
  • A second call replaces the field from the first.
  • The orderByAscending(keyPath:) method writes a separate parameter, so calling both sends both.
  • To sort by a field inside a Group field, pass its dot path, for example bank_offers.discount_in_percentage. See Order By desc Within Group.
  • On a query from stack.taxonomy().query(), the API sorts only on title, created_at, updated_at, published_at and url. See the Taxonomy section of Queries.
  • The method carries the @discardableResult attribute, so a call on a separate line compiles without a warning.

Example

Basic usage: sort entries by price

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .orderByDecending(keyPath: "price_in_usd")
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Sort assets by update date

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
    .orderByDecending(keyPath: "updated_at")
    .find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
        guard case .success(let contentstackResponse) = result else { return }
        for asset in contentstackResponse.items {
            print(asset.fileName)
        }
    }

skip(theFirst:)

skip(theFirst:) skips a number of items before the page that the response returns.

NameTypeDescription
theFirst (required)UInt

Number of items to skip.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • There is no client-side validation. The type is UInt, so a negative number does not compile.
  • Errors that do occur come from the find(_:) call that follows, not from skip(theFirst:).

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

Behavior

  • Client-side only. skip(theFirst:) writes the skip URL parameter and makes no request. The find(_:) method sends it. See Skip.
  • A second call replaces the first value.
  • To read page n of size s, skip n × s items and set the page size with limit(to:). Ask for the total with include(params: .count) to know when to stop. See Pagination.
  • The method carries the @discardableResult attribute, so a call on a separate line compiles without a warning.

Example

Basic usage: read the second page of ten entries

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .skip(theFirst: 10)
    .limit(to: 10)
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Read a later page with the total count

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let page: ContentstackResponse<EntryModel> = try await stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
        .include(params: .count)
        .skip(theFirst: 40)
        .limit(to: 20)
        .find()
    print("Showing \(page.items.count) of \(page.count ?? 0) entries")
} catch {
    print(error)
}

where(valueAtKeyPath:_:)

where(valueAtKeyPath:_:) adds a condition that matches items by the value of one field.

NameTypeDescription
valueAtKeyPath (required)String

UID or dot path of the field to match.

Default: Not applicable
operation (required)Query.Operation

Operator and value the field must match.

Default: Not applicable

Returns: Self. The same query, for chaining.

Validation

  • There is no client-side validation. The SDK does not check that the field exists.
  • Errors that do occur come from the find(_:) call that follows, not from where(valueAtKeyPath:_:).

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

Behavior

  • Client-side only. where(valueAtKeyPath:_:) writes {"<valueAtKeyPath>": <condition>} into the queryParameter dictionary and makes no request. The find(_:) method sends it as JSON in the query parameter. See Equals Operator.
  • The Query.Operation table on the Query page lists each operator and the value format the SDK writes.
  • A second condition on the same field replaces the first. On a Query, use the operator(_:) method for two conditions on one field.
  • To filter on a field inside a Group or Modular Blocks field, pass its dot path, for example bank_offers.card_type. See Equals Operator Within Group.
  • The method works on entry, asset and content type queries. Query also offers where(valueAtKey:_:), which does the same and returns Query.

Example

Basic usage: match entries by a field value

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .where(valueAtKeyPath: "price_in_usd", .isLessThanOrEqual(600))
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let contentstackResponse):
            for entry in contentstackResponse.items {
                print(entry.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Match assets by file name

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
    .where(valueAtKeyPath: "filename", .matches("^banner"))
    .find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
        guard case .success(let contentstackResponse) = result else { return }
        for asset in contentstackResponse.items {
            print(asset.fileName, asset.url)
        }
    }

Match entries that have a value in a field

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
    .where(valueAtKeyPath: "price_in_usd", .exists(true))
    .find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
        guard case .success(let contentstackResponse) = result else { return }
        for entry in contentstackResponse.items {
            print(entry.title)
        }
    }