cs-icon.svg

Contentstack - Swift SDK

Swift Delivery SDK for Contentstack

Contentstack is a headless CMS with an API-first approach. It is a CMS that developers can use to build powerful cross-platform applications in their favorite languages. Build your application frontend, and Contentstack will take care of the rest. Read More.

Contentstack provides Swift Delivery SDK to build application on top of Swift. Given below is the detailed guide and helpful resources to get started with our Swift Delivery SDK.

The Swift Delivery SDK can also be used to create iOS, Apple TV and Mac applications.

Prerequisite

Latest Xcode and Mac OS X

Setup and Installation

To use this SDK on iOS platform, you will have to install the SDK according to the steps given below.

CocoaPods

  • Add the following line to your Podfile
pod ‘ContentstackSwift
  • Run pod install, and you should now have the latest Contentstack release.

Import Header/Module

 import ContentstackSwift

Quickstart in 5 mins

Initializing your SDK

To start using the SDK in your application, you will need to initialize the stack by providing the required keys and values associated with them:

let stack:Stack = Contentstack.stack(apiKey: API_KEY, deliveryToken: DELIVERY_TOKEN, environment: ENVIRONMENT)

To get the api credentials mentioned above, you need to log into your Contentstack account and then in your top panel navigation, go to Settings -> Stack to view both your API Key and your Delivery Token

The stack object that is returned is a Contentstack client object, which can be used to initialize different modules and make queries against our Content Delivery API. The initialization process for each module is explained in the following section.

Querying content from your stack

To fetch all entries of of a content type, use the query given below:

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query()
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
      switch result {
      case .success(let contentstackResponse):
      case .failure(let error):
      }
 }

To fetch a specific entry from a content type, use the following query:

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry(uid: UID)
.fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
     switch result {
     case .success(let model):
     case .failure(let error):
     }
 }

Paginating Responses

In a single instance, the Get Multiple Entries query will retrieve only the first 100 items of the specified content type. You can paginate and retrieve the rest of the items in batches using the skip and limit parameters in subsequent requests.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).query()
.skip(20).limit(20).find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
      switch result {
      case .success(let contentstackResponse):
      case .failure(let error):
      }
}

Querying Assets from your stack

To get a single asset, you need to specify the UID of the asset.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset(uid: "<ASSET_UID>")
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
   switch result {
   case .success(let model):
   case .failure(let error):
   }
}

To retrieve multiple assets. You can also specify search parameters to filter results.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
    switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
    }
}

Contentstack

Create a new Stack instance with stack’s apikey, deliveryToken, environment name and config.

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

Create a new Stack instance with stack’s API key, delivery token, environment name and config.

Returns:
Type
Stack
NameTypeDescription

apiKey (required)

string

stack apiKey.

deliveryToken (required)

String

stack delivery token.

environment (required)

String

environment name in which to perform action.

region

Contentstack region

host

string

Name of Contentstack api server.

apiVersion

string

API version of Contentstack api server.

config

ContentstackConfig

Config of stack.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")

ContentstackConfig

NameTypeDescription

dateDecodingStrategy

JSONDecoder.DateDecodingStrategy

An optional configuration to override the date decoding strategy that is provided by the the SDK.

timeZone

TimeZone

An optional configuration to override the TimeZone the SDK will use to decode Date instances. The SDK will use a TimeZone with 0 seconds offset from GMT if this configuration is omitted.

sessionConfiguration

URLSessionConfiguration

The configuration for the URLSession. Note that HTTP headers will be overwritten internally by the SDK so that requests can be authorized correctly.

setEarlyAccess

With the setEarlyAccess header support, you can access features that are part of the early access program.

Returns:
Type
config

Example:

var config = ContentstackConfig()
let earlyAccess : [String] = ["Taxonomy","Teams"]
config.setEarlyAccess(earlyAccess)
let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")

ContentstackRegion

Contentstack Regions.

  • us: This region is for US cloud
  • eu: This region is for EU cloud
  • azure_na: This region is for Azure-NA cloud
  • azure_eu: This region is for Azure-EU cloud
  • gcp_na: This region is for GCP-NA cloud
NameTypeDescription

us

ContentstackRegion

This region is for US Cloud.

eu

ContentstackRegion

This region is for EU Cloud.

azure_na

ContentstackRegion

This region is for AZURE-NA Cloud.

azure_eu

ContentstackRegion

This region is for AZURE-EU Cloud

gcp_na

ContentstackRegion

This region is for GCP-NA cloud

ContentstackResponse

This is the result of any request of collection from Contentstack.

NameTypeDescription

items

[ItemType]

The resources which are part of the array response.

limit

UInt

The maximum number of resources originally requested.

skip

UInt

The number of elements skipped when performing the request.

count

UInt

The total number of resources which matched the original request.

fields

[String : Any]

The dictionary of fields from the response that are included in API request.

Stack

Stack is instance for performing Contentstack Delivery API request.

NameTypeDescription

apiKey (required)

String

API Key is a unique key assigned to each stack.

deliveryToken (required)

String

Delivery Token is a read-only credential that you can create for different environments of your stack.

environment (required)

String

Environment can be defined as one or more content delivery destinations

host

String

The domain host to perform requests against.

Default: cdn.contentstack.io

region

String

Region refers to the location of the data centers where your organization’s data resides.

apiVersion

string

Stack api version point.

Default: v3

branch

String

Branch for the stack to get data from.

cachePolicy

CachePolicy

CachePolicy allows you to cache request

jsonDecoder

JSONDecoder

The JSONDecoder that the receiving client instance uses to deserialize JSON. The SDK will inject information about the locales to this decoder and use this information to normalize the fields dictionary of entries and assets.

contentType(uid:)

Get instance of ContentType to fetch content-types and schema or fetch entries of specific content-type.

Returns:
Type
ContentType
NameTypeDescription

uid

String

The UId of ContentType you want to fetch data,

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType()
stack.contentType(uid: "<CONTENT_TYPE_UID>")

asset(uid:)

Get instance of Asset to fetch Assets or fetch specific Asset.

Returns:
Type
Asset
NameTypeDescription

uid

String

The UId of Asset you want to fetch data.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset()
stack.asset(uid: "<ASSET_UID>")

sync(_:syncTypes:then:)

The Initial Sync request performs a complete sync of your app data. It returns all the published entries and assets of the specified stack in response. The response also contains a sync_token, which you get in SyncStack, since this token is used to get subsequent delta updates later.

Returns:
Type
SyncStack
NameTypeDescription

syncStack

SyncStack

The relevant SyncStack to perform the subsequent sync on. Defaults to a new empty instance of SyncStack.

syncTypes

SyncableTypes

SyncableTypes that can be sync.

completion (required)

A handler which will be called on completion of the operation.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.sync { (result: Result<SyncStack, Error>) in
    switch result {
    case .success(let syncStack):
    case .failure(let error):
    }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
let syncStack = SyncStack(paginationToken: paginationToken)
stack.sync(syncStack, then: { (result: Result<SyncStack, Error>) in
    switch result {
    case .success(let syncStack):
    case .failure(let error):
    }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
let syncStack = SyncStack(syncToken: syncToken)
stack.sync(syncStack, then: { (result: Result<SyncStack, Error>) in
    switch result {
    case .success(let syncStack):
    case .failure(let error):
    }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.sync(syncTypes: [.publishType(.assetPublished)], then: { (result: Result<SyncStack, Error>) in
    switch result {
    case .success(let syncStack):
    case .failure(let error):
    }
}

CachePolicy

The cache policies allow you to define the source from where the SDK will retrieve the content.

NameTypeDescription

networkOnly

CachePolicy

The SDK retrieves data through a network call, and saves the retrieved data in the cache. This is set as the default policy.

cacheOnly

CachePolicy

The SDK gets data from the cache.

cacheElseNetwork

CachePolicy

The SDK gets data from the cache. However, if it fails to retrieve data from the cache, it makes a network call.

networkElseCache

CachePolicy

The SDK gets data using a network call. However, if the call fails, it retrieves data from cache.

cacheThenNetwork

CachePolicy

The SDK gets data from cache, and then makes a network call. (A success callback will be invoked twice.

SyncStack

A container for the synchronized state of a Stack

NameTypeDescription

syncToken

String

You can use the sync_token later to perform subsequent sync, which fetches only new changes through delta updates.

paginationToken

string

If there are more than 100 records, you get a pagination_token in response. This token can be used to fetch the next batch of data.

totalCount

Int

The total number of resources which matched the original request.

items

[Any]

The resources which are part of the array response.

init(syncToken:paginationToken:)

Initialization method for the SyncStack.

Returns:
Type
SyncStack
NameTypeDescription

syncToken

String

The syncToken from the previous syncronization.

paginationToken

String

The paginationToken to fetch next batch of data.

SyncableTypes

This enable to sync entity with condition.

NameTypeDescription

all

SyncableTypes

Sync all assets and all entries of all content types.

contentType(String)

SyncableTypes

Enter content type UIDs. e.g., products. This retrieves published entries of specified content type.

locale(String)

SyncableTypes

Enter locale codes. e.g., en-us This retrieves published entries of specific locale.

startFrom(Date)

SyncableTypes

Enter the start date. e.g., Date() This retrieves published entries starting from a specific date.

publishType(PublishType)

SyncableTypes

If you do not specify any value from PublishType, it will bring all published entries and published assets. You can pass multiple types as comma-separated values.

PublishType

This enable to sync entity with Published type.

NameTypeDescription

entryPublished

PublishType

To sync only Published Entries.

assetPublished

PublishType

To sync only Published Assets.

entryUnpublished

PublishType

To sync only Unpublished Entries.

assetUnpublished

PublishType

To sync only Unpublished Assets.

entryDeleted

PublishType

To sync only Deleted Entries.

assetDeleted

PublishType

To sync only Deleted Assets.

contentTypeDeleted

PublishType

To sync only only deleted content type Entries.

ImageTransform

The Image Delivery API is used to retrieve, manipulate and/or convert image files of your Contentstack account and deliver it to your web or mobile properties.

auto()

The auto parameter lets you enable the functionality that automates certain image optimization features.

Returns:
Type
ImageTransform
let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().auto()
let result = urlString.url(with: transform)

quality(_:)

The quality parameter lets you control the compression level of images that have Lossy file format. The value for this parameters can be entered in any whole number (taken as a percentage) between 1 and 100.

Returns:
Type
ImageTransform
NameTypeDescription

quality (required)

UInt

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().quality(10)
let result = urlString.url(with: transform)

format(_:)

The format parameter lets you converts a given image from one format to another.

Returns:
Type
ImageTransform
NameTypeDescription

format (required)

Format

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().format(Format.gif)
let result = urlString.url(with: transform)

resize(_:)

The width parameter lets you dynamically resize the width of the image by specifying pixels or percentage. The height parameter lets you dynamically resize the height of the image by specifying pixels or percentage. The disable parameter disables the functionality that is enabled by default.

Returns:
Type
ImageTransform
NameTypeDescription

resize (required)

Resize

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().resize(Resize(size: Size(width: width)))
let result = urlString.url(with: transform)

crop(_:)

The crop parameter allows you to remove pixels from an image.

Returns:
Type
ImageTransform
NameTypeDescription

crop (required)

Crop

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().crop(.offset(width: 100, height: 100, xOffset: 0.5, yOffset: 0.7))
let result = urlString.url(with: transform)

canvas(_:)

The canvas parameter allows you to increase the size of the canvas that surrounds an image.

Returns:
Type
ImageTransform
NameTypeDescription

canvas (required)

Canvas

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().canvas(.offset(width: 100, height: 100, xOffset: 0.5, yOffset: 0.7))
let result = urlString.url(with: transform)

fit(_:)

The fit parameter enables you to fit the given image properly within the specified height and width. You need to provide values for the height, width and fit parameters.

Returns:
Type
ImageTransform
NameTypeDescription

fit (required)

Fit

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().fit(.bounds(Size(width: 100, height: 100)))
let result = urlString.url(with: transform)

trim(_:)

The trim parameter lets you trim an image from the edges.

Returns:
Type
ImageTransform
NameTypeDescription

edgeInset (required)

NSEdgeInsets

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().trim(NSEdgeInsets(top: 50, left: 20, bottom: 50, right: 20))
let result = urlString.url(with: transform)

orient(_:)

The orient parameter lets you control the cardinal orientation of the given image.

Returns:
Type
ImageTransform
NameTypeDescription

orient (required)

Orientation

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().orient(.default)
let result = urlString.url(with: transform)

overlay(relativeUrl:overlayTypes:)

The overlay parameter allows you to put one image on top of another. You need to specify the relative URL of the image as value for this parameter.

Returns:
Type
ImageTransform
NameTypeDescription

relativeUrl (required)

String

overlayTypes

[OverlayType]

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let relativeUrl = "<RELATIVE_URL>"
let transform = ImageTransform().overlay(relativeUrl: relativeUrl, 
                 overlayTypes: [
                    .align(.left),
                    .repeat(.both),
                    .size(Size(width: width, height: height))
                 ]))
let result = urlString.url(with: transform)

overlay(relativeUrl:padding:)

The overlay-pad parameter allows you to add padding pixels to the edges of an overlay image. You need to specify the relative URL of the image as value for this parameter.

Returns:
Type
ImageTransform
NameTypeDescription

relativeUrl (required)

String

padding (required)

NSEdgeInsets

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let relativeUrl = "<RELATIVE_URL>"
let transform = ImageTransform().overlay(relativeUrl: relativeUrl, padding: NSEdgeInsets(top: 50, left: 20, bottom: 50, right: 20))
let result = urlString.url(with: transform)

pad(_:)

The pad parameter lets you add extra pixels to the edges of an image. This is useful if you want to add whitespace or border to an image. The value for this parameter can be given in pixels or percentage.

Returns:
Type
ImageTransform
NameTypeDescription

padding (required)

NSEdgeInsets

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().pad(NSEdgeInsets(top: 50, left: 20, bottom: 50, right: 20))
let result = urlString.url(with: transform)

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().pad(UIEdgeInsets(top: 50, left: 20, bottom: 50, right: 20))
let result = urlString.url(with: transform)

backgroundColor(_:)

The bg-color parameter lets you set a backgroud color for the given image.

Returns:
Type
ImageTransform
NameTypeDescription

color (required)

Color

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().backgroundColor(.hex("AAFF00")))
let result = urlString.url(with: transform)

dpr(_:resize:)

The dpr parameter lets you deliver images with appropriate size to devices that come with a defined device pixel ratio.

Returns:
Type
ImageTransform
NameTypeDescription

dpr (required)

UInt

resize (required)

Resize

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().dpr(1000, resize: Resize(size: Size(width: 320))))
let result = urlString.url(with: transform)

blur(_:)

The blur parameter allows you to decrease the focus and clarity of a given image.

Returns:
Type
ImageTransform
NameTypeDescription

blur (required)

UInt

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().blur(10)
let result = urlString.url(with: transform)

saturation(_:)

The saturation parameter allows you to increase or decrease the intensity of the colors in a given image.

Returns:
Type
ImageTransform
NameTypeDescription

value

Double

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().saturation(10)
let result = urlString.url(with: transform)

contrast(_:)

The contrast parameter allows you to increase or decrease the difference between the darkest and lightest tones in a given image.

Returns:
Type
ImageTransform
NameTypeDescription

value

Double

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().contrast(10)
let result = urlString.url(with: transform)

brightness(_:)

The brightness parameter allows you to increase or decrease the intensity with which an image reflects or radiates perceived light.

Returns:
Type
ImageTransform
NameTypeDescription

value

Double

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().brightness(10)
let result = urlString.url(with: transform)

fetchFirstFrame()

The frame parameter fetches the first frame from an animated GIF (Graphics Interchange Format) file that comprises a sequence of moving images.

Returns:
Type
ImageTransform
let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().fetchFirstFrame()
let result = urlString.url(with: transform)

sharpen(amount:radius:threshold:)

The sharpen parameter allows you to increase the definition of the edges of objects in an image.

Returns:
Type
ImageTransform
NameTypeDescription

amount (required)

UInt

radius

UInt

threshold

UInt

let urlString = "<IMAGE_URL_TO_TRANSFORM>"
let transform = ImageTransform().sharpen(amount: 11, radius: 2, threshold: 100)
let result = urlString.url(with: transform)

Canvas

The canvas parameter allows you to increase the size of the canvas that surrounds an image.

NameTypeDescription

default(width: UInt, height: UInt)

Canvas

Crop by width and height.

aspectRatio(Size, ratio: String)

Canvas

Crop by aspect ratio.

region(width: UInt, height: UInt, xRegion: Double, yRegion: Double)

Canvas

Crop sub region.

offset(width: UInt, height: UInt, xOffset: Double, yOffset: Double)

Canvas

Crop and offset.

Color

The bg-color parameter lets you set a backgroud color for the given image.

NameTypeDescription

hex(String)

Color

Hexadecimal value should be 3-digit or 6-digit.

rgb(red: UInt, green: UInt, blue: UInt)

Color

Red, Blue, Green value which defines the intensity of the corresponding color, with the value ranging anywhere between 0 and 255 for each.

rgba(red: UInt, green: UInt, blue: UInt, alpha: Double)

Color

Red, Blue, Green value which defines the intensity of the corresponding color, with the value ranging anywhere between 0 and 255 for each. The alpha value defines the transparency, with 0.0 being fully transparent and 1.0 being completely opaque.

ContentstackLogger

An enum describing the types of messages to be logged.

NameTypeDescription

logType

LogType

The type of logger used to log messages; defaults to NSLog on iOS, tvOS, watchOS, macOS. Defaults to print on other platforms.

Default: NSLog

logLevel

LogLevel

The highest order of message types that should be logged.

Default: LogLevel.error

LogLevel

An enum describing the types of messages to be logged.

NameTypeDescription

none

LogLevel

Log nothing to the console.

error

LogLevel

Only log errors to the console.

info

LogLevel

Log messages when requests are sent, and when responses are received, as well as other useful information.

LogType

The type of logger to use.

NameTypeDescription

print

LogType

Log using simple Swift print statements.

nsLog

LogType

Log using NSLog.

custom(CustomLogger)

ContentstackRegion

Log using a custom logger.

Fit

The fit parameter enables you to fit the given image properly within the specified height and width. You need to provide values for the height, width and fit parameters

NameTypeDescription

bounds(Size)

Fit

If fit is set to bounds, it will constrain the given image into the specified height and width.

crop(Size)

Fit

If fit is set to crop, it will crop the given image to the defined height and width.

Crop

The crop parameter allows you to remove pixels from an image.

NameTypeDescription

default(width: UInt, height: UInt)

Crop

Crop by width and height.

aspectRatio(Size, ratio: String, mode: Mode = .none)

Crop

Crop by aspect ratio.

region(width: UInt, height: UInt, xRegion: Double, yRegion: Double, mode: Mode = .none)

Crop

Crop sub region.

offset(width: UInt, height: UInt, xOffset: Double, yOffset: Double, mode: Mode = .none)

Crop

Crop and offset.

Format

The format parameter lets you converts a given image from one format to another.

NameTypeDescription

pjpg

Format

Progressive JPEG Format

jpeg

Format

JPEG format.

gif

Format

GIF format.



png

Format

PNG format.

webp

Format

WEBP format.

webply

Format

WEBP Lossy format.

webpll

Format

WEBP Lossless format.

Orientation

The orient parameter lets you control the cardinal orientation of the given image.

NameTypeDescription

default

Orientation

Set image to default

flipHorizontal

Orientation

Flip image horizontally.

flipHorizontalVertical

Orientation

Flip image horizontally and vertically.

flipVerticle

Orientation

Flip image vertically.

flipHorizontalLeft

Orientation

Flip image horizontally and then rotate 90 degrees towards left.

right

Orientation

Rotate image 90 degrees towards right

flipHorizontalRight

Orientation

Flip image horizontally and then rotate 90 degrees towards right.

left

Orientation

Rotate image 90 degrees towards left.

OverlayAlign

The overlay-align parameter lets you define the position of the overlay image.

NameTypeDescription

top

OverlayAlign

Align the overlay image to the top of the actual image.

bottom

OverlayAlign

Align the overlay image to the bottom of the actual image.

left

OverlayAlign

Align the overlay image to the left of the actual image.

right

OverlayAlign

Align the overlay image to the right of the actual image.

middle

OverlayAlign

Align the overlay image to the middle (vertically) of the actual image.

center

OverlayAlign

Align the overlay image to the center (horizontally) of the actual image.

topLeft

OverlayAlign

Align the overlay image to the top-left of the actual image.

topRight

OverlayAlign

Align the overlay image to the top-right of the actual image.

bottomLeft

OverlayAlign

Align the overlay image to the bottom-left of the actual image.

bottomRight

OverlayAlign

Align the overlay image to the bottom-right of the actual image.

OverlayRepeat

The overlay-repeat parameter lets you define how the overlay image will be repeated on the given image.

NameTypeDescription

both

OverlayRepeat

The overlay-repeat parameter for both.

horizontal

OverlayRepeat

The overlay-repeat parameter horizontal

verticle

OverlayRepeat

The overlay-repeat parameter verticle.

OverlayType

The overlay parameter allows you to put one image on top of another. You need to specify the relative URL of the image as value for this parameter. SeeOverlay Settings

NameTypeDescription

align(OverlayAlign)

OverlayType

The overlay-align parameter lets you define the position of the overlay image.

repeat(OverlayRepeat)

OverlayType

The overlay-repeat parameter lets you define how the overlay image will be repeated on the given image.

size(Size)

OverlayType

The overlay-width parameter lets you define the width of the overlay image. Theoverlay-height parameter lets you define the height of the overlay image.

ResizeFilter

The resize-filter parameter allows you to use the resizing filter to increase or decrease the number of pixels in a given image.

NameTypeDescription

none

ResizeFilter

Default to none allow not to set Resize-filter

nearest

ResizeFilter

Utilizes the values of the neighbouring translated pixels to provide smoother and quick resizing of a given image.

bilinare

ResizeFilter

Utilizes a 2x2 environment of pixels on an average. This filter blends new interpolated pixels with the original image pixels to generate a larger image with more detail.

bicubic

ResizeFilter

Utilizes a 4x4 environment of pixels on average. This filter maintains the innermost pixels and discards all the extra details from a given image.

lanczos2

ResizeFilter

Enhances the ability to identify linear features and object edges of a given image. This filter uses the sinc resampling function to reconstruct the pixelation of an image and improve its quality.

lanczos3

ResizeFilter

Enhances the ability to identify linear features and object edges of a given image. This filter uses the since resampling function to reconstruct the pixelation of an image and improve its quality.

ResponseType

The response type define the source from where the SDK retrieve the content.

NameTypeDescription

cache

ResponseType

This specifies response is from cache.

network

ResponseType

This specifies response is from network call.

ImageTransformError

Information regarding an error received from Contentstack’s Image Delivery API.

NameTypeDescription

debugDescription

String

Error description.

Resize

The width parameter lets you dynamically resize the width of the image by specifying pixels or percentage. The height parameter lets you dynamically resize the height of the image by specifying pixels or percentage. The disable parameter disables the functionality that is enabled by default. See Resize Images.

NameTypeDescription

size

Size

The Size parameter lets you dynamically resize the width and height of the output image by specifying pixels or percentage values.

disableUpscale

Bool

This disableUpscale ensures that even if the specified height or width is much bigger than the actual image, it will not be rendered disproportionately.

filter

ResizeFilter

The resize-filter parameter allows you to use the r esizing filter to increase or decrease the number of pixels in a given image.

Size

The Size parameter lets you dynamically resize the width and height of the output image by specifying pixels or percentage values.

NameTypeDescription

width

UInt

The width parameter lets you dynamically resize the width of the output image by specifying pixels or percentage values.

height

UInt

The height parameter lets you dynamically resize the height of the output image by specifying pixels or percentage values.

ErrorInfo

A description about detailed error information.

NameTypeDescription

apiKey

[String]

A pseudo identifier for the error returned by the API(s). “InvalidAPIKey” is example.

deliveryToken

[String]

A pseudo identifier for the error returned by the API(s). “InvalidDeliveryToken” is example.

environment

[String]

A pseudo identifier for the error returned by the API(s). “InvalidEnvironment” is example.

uid

[String]

A pseudo identifier for the error returned by the API(s). “InvalidUID” is example.

APIError

Information regarding an error received from Contentstack’s API.

NameTypeDescription

debugDescription

String

Error description.

errorMessage

String

Human readable error Message

errorCode

Int

Error Code from API.

errorInfo

ErrorInfo

More detailed error Information.

statusCode

Int

The HTTP status code.

SystemFields

System Fields are available fields for entities in Contentstack.

NameTypeDescription

uid

String

The unique identifier of the entity.

title

String

The title of the entity.

createdAt

Date

Describes the date of the entity is created.

updatedAt

Date

Describes the date of the entity is last updated.

AssetFields

The Protocol for creating Asset model.

NameTypeDescription

createdBy

String?

Describes the unique identifier of user who created the entity.

updatedBy

String?

Describes the unique identifier of user who last updated the entity.

fileName

String

The name of the Asset.

fileSize

String

The size of the Asset.

fileType

String

The file type of the Asset.

url

String

The url for the Asset.

Asset

Asset refer to all the media files (images, videos, PDFs, audio files, and so on) uploaded in your Contentstack repository for future use.

NameTypeDescription

cachePolicy

CachePolicy

Set cache policy for the Asset request.

includeRelativeURL()

To include the relative URLs of the assets in the response.

Returns:
Type
Asset
let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset(uid: "<ASSET_UID>").includeRelativeURL()

includeFallback()

To include the fallback published content if specified locale content is not publish.

Returns:
Type
Asset
let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset(uid: "<ASSET_UID>").includeFallback()

includeDimension()

To include the dimensions (height and width) of the image in the response.

Returns:
Type
Asset
let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset(uid: "<ASSET_UID>").includeDimension()

includeMetadata()

Includes Asset metadata along with response body.

Returns:
Type
Asset

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRNOMENT")
stack.asset(uid:"ASSET_UID").includeFallback()

query()

To fetch all or find Assets query method is used.

Returns:
Type
AssetQuery
let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()

fetch(_:)

This call fetches the latest version of a specific Asset of a particular stack.

Returns:
Type
void
NameTypeDescription

completion (required)

Result<ResourceType, Error>, ResponseType) -> Void

A handler which will be called on completion of the operation.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset(uid: "<ASSET_UID>")
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
   switch result {
   case .success(let model):
   case .failure(let error):
   }
}

AssetQuery

To fetch all or find Assets use AssetQuery.

NameTypeDescription

cachePolicy

CachePolicy

Set cache policy for the AssetQuery request.

stack

Stack

Stack instance for AssetQuery to be fetched



parameters

[String : Any]

URI Parameters.

queryParameter

[String : Any]

Query parameter

where(queryableCodingKey:_:)

Use this method to do a search on Assets which enables searching for entries based on value’s for members of referenced entries.

Returns:
Type
Self
NameTypeDescription

queryableCodingKey (required)

AssetModel.QueryableCodingKey

The member of your QueryableCodingKey that you are performing your select operation against.

operation (required)

Query.Operation

The query operation used in the query.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.where(queryableCodingKey: .title, .equals("Asset Title"))
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
    switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
    }
}

include(params:)

Include URI paramertes to fetch Asset with relative url and dimension.

Returns:
Type
Self
NameTypeDescription

params (required)

AssetQuery.Include

The member of your AssetQuery.Include that you want to include in response

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query().include(params: [.all])
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
    switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
        //Error Message
    }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query().include(params: [.count]) 
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in 
  switch result { 
  case .success(let contentstackResponse): 
  case .failure(let error): 
  }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query().include(params: [.relativeURL])
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
    switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
    }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query().include(params: [.dimension]) 
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in 
  switch result { 
  case .success(let contentstackResponse): 
  case .failure(let error): 
  }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query().include(params: [.fallback]) 
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in 
  switch result { 
  case .success(let contentstackResponse): 
  case .failure(let error): 
  }
}

AssetQuery.Include

The AssetQuery.Include is parameter for including count, relative URLs, and dimensions in result.

NameTypeDescription

count

AssetQuery.Include

To include count in the response.



relativeURL

AssetQuery.Include

To include the relative URLs of the assets in the response.

dimension

AssetQuery.Include

To include the dimensions (height and width) of the image in the response. Supported image types: JPG, GIF, PNG, WebP, BMP, TIFF, SVG, and PSD.

fallback

AssetQuery.Include

Retrieve the published content of the fallback locale if an entry is not localized in specified locale.

all

AssetQuery.Include

To include all AssetQuery.Include values.

ContentType

Content type defines the structure or schema of a page or a section of your web or mobile property.

NameTypeDescription

cachePolicy

CachePolicy

Set cache policy for the ContentType request.

entry(uid:)

Get instance of Entry to fetch Entry or fetch specific Entry.

Returns:
Type
ContentType
let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry()

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry(uid: "<ENTRY_UID>")

includeGlobalFields()

To include Global Fields schema in ContentType response.

Returns:
Type
ContentType
let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").includeGlobalFields()
.fetch { (result: Result<ContentTypeModel, Error>, response: ResponseType) in
   switch result {
   case .success(let model):
   case .failure(let error):
   }
}

query()

To fetch all or find ContentTypes query method is used.

Returns:
Type
ContentTypeQuery
let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()

fetch(_:)

This call fetches the latest version of a specific ContentType of a particular stack.

Returns:
Type
void
NameTypeDescription

completion (required)

Result<ResourceType, Error>, ResponseType) -> Void

A handler which will be called on completion of the operation.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>")
.fetch { (result: Result<ContentTypeModel, Error>, response: ResponseType) in
   switch result {
   case .success(let model):
   case .failure(let error):
   }
}

ContentTypeDecodable

The decodable to get schema for ContentType.

ContentTypeQuery

To fetch all or find ContentType use ContentTypeQuery.

NameTypeDescription

cachePolicy

CachePolicy

Set cache policy for the ContentTypeQuery request.

stack

Stack

Stack instance for ContentTypeQuery to be fetched



parameters

[String : Any]

URI Parameters.

queryParameter

[String : Any]

Query parameter

where(queryableCodingKey:_:)

Use this method to do a search on ContentType which enables searching for entries based on value’s for members of referenced entries.

Returns:
Type
Self
NameTypeDescription

queryableCodingKey (required)

ContentTypeModel.QueryableCodingKey

The member of your QueryableCodingKey that you are performing your select operation against.

operation (required)

Query.Operation

The query operation used in the query.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.where(queryableCodingKey: .title, .equals("ContentType Title"))
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
    switch result {
    case .success(let contentstackResponse):
        // Contentstack response with ContentTypeModel array in items.
    case .failure(let error):
        //Error Message
    }
}

include(params:)

Include URI parametes to fetch ContentType with Global Fields and Count.

Returns:
Type
Self
NameTypeDescription

params (required)

ContentTypeQuery.Include

The member of your ContentTypeQuery.Include that you want to include in response

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query().include(params: [.all])
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
    switch result {
    case .success(let contentstackResponse):
        // Contentstack response with ContentTypeModel array in items.
    case .failure(let error):
        //Error Message
    }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query().include(params: [.count]) 
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in 
  switch result { 
  case .success(let contentstackResponse): 
  case .failure(let error): 
  }
}

includeMetadata()

Includes ContentTypeQuery metadata along with response body

Returns:
Type
ContentTypeQuery
let stack = Contentstack.stack(apiKey: apiKey,
 deliveryToken: deliveryToken,
  environment: environment)
  
stack.contentType(uid: contentTypeUID).entry().includeMetadata().query()

ContentTypeQuery.Include

The `ContentTypeQuery.Include` is parameter for including count, Global Fields schema in result.

NameTypeDescription

count

ContentTypeQuery.Include

To include count in the response.



globalFields

ContentTypeQuery.Include

To include Global Fields schema in ContentType response,

all

ContentTypeQuery.Include

To include all `ContentTypeQuery.Include` values.

Entry

An Entry is the actual piece of content created using one of the defined content types.

NameTypeDescription

cachePolicy

CachePolicy

Set cache policy for the entry request.

stack

Stack

Stack instance for Entry to be fetched



parameters

[String : Any]

URI Parameters.

queryParameter

[String : Any]

Query parameter

query()

To fetch all or find Entries query method is used.

Returns:
Type
Query
let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
let query = stack.contentType(uid: "<CONTENT_TYPE_UID>").entry(uid: "<ENTRY_UID>").query()

query(_:)

To fetch all or find Entries to specific model query method is used.

Returns:
Type
QueryOn<EntryType>
NameTypeDescription

entry (required)

EntryType.Type

A entry type for querying on.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
let query = stack.contentType(uid: "<CONTENT_TYPE_UID>").entry(uid: "<ENTRY_UID>").query(Product.self)

fetch(_:)

This call fetches the latest version of a specific Entry of a particular stack.

Returns:
Type
void
NameTypeDescription

completion (required)

Result<ResourceType, Error>, ResponseType) -> Void

A handler which will be called on completion of the operation.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry(uid: "<ENTRY_UID>")
.fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
   switch result {
   case .success(let model):
   case .failure(let error):
   }
}

Variants

The variants method retrieves details of a specific entry variant or an array of entry variants based on the applied query.

When Personalize creates a variant in the CMS, it assigns a "Variant Alias" to identify that specific variant. When fetching entry variants using the Delivery API, you can pass variant aliases in place of variant UIDs in the x-cs-variant-uid header.

Returns:
Type
Entry
NameTypeDescription

uid | uids (required)

string | string[]

Enter the UID of the variant

Example 1:

import Contentstack
let stack = Contentstack.stack(
    apiKey: <API_KEY>,
    deliveryToken: <DELIVERY_TOKEN>,
    environment: <ENVIRONMENT>
)
stack
.contentType(uid: <CT_UID>)
.entry(uid: <ENTRY_UID>)
.variants(uid: <VARIANT_UID/VARIANT_ALIAS>)
.fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
    switch result {
        case .success(let contentstackResponse):
            // Contentstack response with variant entry data
        case .failure(let error):
            // Error Message
    }
}

Example 2:

import Contentstack
let stack = Contentstack.stack(
    apiKey: <API_KEY>,
    deliveryToken: <DELIVERY_TOKEN>,
    environment: <ENVIRONMENT>
)
stack
.contentType(uid: <CT_UID>)
.entry(uid: <ENTRY_UID>)
.variants(uids: [<VARIANT_UID_1/VARIANT_ALIAS_1>, <VARIANT_UID_2/<VARIANT_ALIAS_2>, <VARIANT_UID_3/VARIANT_ALIAS_3>])
.fetch { (result: Result<EntryModel, Error>, response: ResponseType) in
    switch result {
        case .success(let contentstackResponse):
            // Contentstack response with variant entry data
        case .failure(let error):
            // Error Message
    }
}

EntryFields

The Protocol for creating Entry model.

NameTypeDescription

locale

String

The code for currently selected locale.

createdBy

String?

Describes the unique identifier of user who created the entity.

updatedBy

String?

Describes the unique identifier of user who last updated the entity.

EntryDecodable

Decodable is a powerful Swift standard library feature that developers can use to decode custom types from external representation, such as JSON.

EntryDecodable is an extension of the decodable protocol that you can use to decode the response to a specific model. By using this protocol, you can define types that will be mapped from your entries of the content type.

In this guide, we will discuss how we can use the EntryDecodable Protocol in your Swift SDK.

EntryDecodable Example Usage

Let’s understand how to use this protocol with the help of a few examples.

Standard Usage

We have a content type named Session and to fetch entries of our Session content type from the Swift SDK, we need to create a class named Session that implements the EntryDecodable protocol as follows:

Example usage:

class Session: EntryDecodable {
public enum FieldKeys: String, CodingKey {
     case title, uid, locale, type, speakers
     case createdAt = "created_at"
     case updatedAt = "updated_at"
     case createdBy = "created_by"
     case updatedBy = "updated_by"
     case sessionId = "session_id"
     case desc = "description"
     case sessionTime = "session_time"
 }
 var locale: String
 var title: String
 var uid: String
 var createdAt: Date?
 var updatedAt: Date?
 var createdBy: String?
 var updatedBy: String?
 var sessionId: Int
 var desc: String
 var type: String
 var sessionTime: SessionTime
 var speakers: [Speaker]?
 public required init(from decoder: Decoder) throws {
     let container   = try decoder.container(keyedBy: FieldKeys.self)
     uid = try container.decode(String.self, forKey: .uid)
     title = try container.decode(String.self, forKey: .title)
     createdBy = try? container.decode(String.self, forKey: .createdBy)
     updatedBy = try? container.decode(String.self, forKey: .updatedBy)
     createdAt = try? container.decode(Date.self, forKey: .createdAt)
     updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
     locale = try container.decode(String.self, forKey: .locale)
     sessionId = try container.decode(Int.self, forKey: .sessionId)
     desc = try container.decode(String.self, forKey: .desc)
     type = try container.decode(String.self, forKey: .type)
     sessionTime = try container.decode(DateTime.self, forKey: .sessionTime)
     speakers = try container.decode([Speaker].self, forKey: .speakers)
  }
}

Usage in Referencing

Let’s say there is another content type in our Stack named Speaker that is referenced in our Session Content Type.

For this case, we will create a class named Speaker that implements the EntryDecodable protocol as follows: Example usage:

class Speaker: EntryDecodable {
  public enum FieldKeys: String, CodingKey {
    case createdAt = "created_at"
    case updatedAt = "updated_at"
    case createdBy = "created_by"
    case updatedBy = "updated_by"
    case desc = "description"
  }
  var locale: String
  var title: String
  var uid: String
  var createdAt: Date?
  var updatedAt: Date?
  var createdBy: String?
  var updatedBy: String?
  var sessionId: Int
  var desc: String
  var name: String
  public required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: FieldKeys.self)
    uid = try container.decode(String.self, forKey: .uid)
    title = try container.decode(String.self, forKey: .title)
    createdBy = try? container.decode(String.self, forKey: .createdBy)
    updatedBy = try? container.decode(String.self, forKey: .updatedBy)
    createdAt = try? container.decode(Date.self, forKey: .createdAt)
    updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
    locale = try container.decode(String.self, forKey: .locale)
    name = try container.decode(String.self, forKey: .name)
    desc = try container.decode(String.self, forKey: .desc)
  }
}

In the Session class, we have a ‘session_time’ Global Field. To parse it, we need to create a class named SessionTime that implements the Decodable protocol as follows.

Example:

class SessionTime: Decodable {
  var startTime: Date?
  var endTime: Date?
  public enum CodingKeys: String, CodingKey {
    case startTime = "start_time"
    case endTime = "end_time"
  }
  public required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    startTime = try? container.decode(Date.self, forKey: .startTime)
    endTime = try? container.decode(Date.self, forKey: .endTime)
  }
}

Note: If we have fields with Modular block, JSON, or an array of JSON in our content type, we can create a class that implements Decodable.

NameTypeDescription

FieldKeys

CodingKey

The CodingKey representing the field identifiers/JSON keys for the corresponding content type. These coding keys should be the same as those used when implementing Decodable.

BaseQuery

A concrete implementation of BaseQuery which serves as the base class for `Query`, `ContentTypeQuery` and `AssetQuery`.

find(_:)

This is a generic find method which can be used to fetch collections of ContentType, Entry, and Asset instances.

Returns:
Type
void
NameTypeDescription

completion (required)

ResultsHandler<ContentstackResponse<ResourceType>>

A handler which will be called on completion of the operation.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

where(valueAtKeyPath:_:)

Method to adding Query.

Returns:
Type
Self
NameTypeDescription

keyPath (required)

string

Key path for field uid.

operation (required)

Query.Operation

The query operation used in the query.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKeyPath: "<FIELD_UID>", .equals("Field condition"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.where(valueAtKeyPath: "<FIELD_UID>", .equals("Field condition"))
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.where(valueAtKeyPath: "<FIELD_UID>", .equals("Field condition"))
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

skip(theFirst:)

Instance method to mutating query to skip the first n records.

Returns:
Type
Self
NameTypeDescription

numberOfResults (required)

UInt

The number of results that will be skipped in the query.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.skip(theFirst: 20)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.skip(theFirst: 20)
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.skip(theFirst: 20)
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

limit(to:)

Instance method to mutating query to limit response to contain n values.

Returns:
Type
Self
NameTypeDescription

numberOfResults (required)

UInt

The number of results the response will be limited to.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.limit(to: 20)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.limit(to: 20)
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.limit(to: 20)
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

orderByAscending(keyPath:)

Instance method to ordering the response in ascending for specific field.

Returns:
Type
Self
NameTypeDescription

keyPath (required)

String

The key path for the property you are performing ordering.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.orderByAscending(keyPath: “<FIELD_UID>”)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.orderByAscending(keyPath: “<FIELD_UID>”)
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.orderByAscending(keyPath: “<FIELD_UID>”)
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

orderByDecending(keyPath:)

Instance method to ordering the response in descending for specific field.

Returns:
Type
Self
NameTypeDescription

keyPath (required)

String

The key path for the property you are performing ordering.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.orderByDecending(keyPath: “<FIELD_UID>”)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.orderByDecending(keyPath: “<FIELD_UID>”)
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.orderByDecending(keyPath: “<FIELD_UID>”)
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

addURIParam(dictionary:)

The parameters dictionary that are converted to URLComponents.

Returns:
Type
Self
NameTypeDescription

dictionary (required)

[String : Any]

The dictionary for URLComponents

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.addURIParam(dictionary: ["key": "value"])
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.addURIParam(dictionary: ["key": "value"])
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.addURIParam(dictionary: ["key": "value"])
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

addURIParam(with:value:)

The parameters dictionary that are converted to URLComponents.

Returns:
Type
Self
NameTypeDescription

key (required)

string

The key for query parameter,

value

string

The value for query parameter.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.addURIParam(with: “key”, value: “value”)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.addURIParam(with: “key”, value: “value”)
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.addURIParam(with: “key”, value: “value”)
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

addQuery(dictionary:)

The Query parameters dictionary that are converted to URLComponents.

Returns:
Type
Self
NameTypeDescription

dictionary (required)

[String : Any]

The dictionary for URLComponents

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.addQuery(dictionary: ["key": "value"])
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.addQuery(dictionary: ["key": "value"])
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.addQuery(dictionary: ["key": "value"])
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

addQuery(with:value:)

The Query parameters dictionary that are converted to URLComponents.

Returns:
Type
Self
NameTypeDescription

key (required)

string

The key for query parameter.

value (required)

Any

The value for query parameter.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.addQuery(with: "key", value: "value")
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType().query()
.addQuery(with: "key", value: "value")
.find { (result: Result<ContentstackResponse<ContentTypeModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.asset().query()
.addQuery(with: "key", value: "value")
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

Query

To fetch all or find Entries use Query.

NameTypeDescription

stack

Stack

Stack instance for the Query.

parameters

[String : Any]

URI parameter

queryParameter

[String : Any]

Query parameters.

cachePolicy

CachePolicy

To set the cache policy for the query request.

where(valueAtKey:_:)

Use this method to do a search on Entries which enables searching for entries based on value’s for field key Path.

Returns:
Type
Query
NameTypeDescription

path (required)

string

The field key path that you are performing your select operation against.

operation (required)

Query.Operation

The query operation used in the query.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", .equals("Entry Title"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", .notEquals("Entry Title"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", .includes(["one", "two"])
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", .excludes(["three", "four"]))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", .isLessThan(10))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", .isLessThanOrEqual(10))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", .isGreaterThan(10))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", .isGreaterThanOrEqual(10))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", exists(true))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKey: "<FIELD_UID>", .matches("^[a-z]"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

where(queryableCodingKey:_:)

Use this method to do a search on Entries which enables searching for entries based on value’s for members of referenced entries.

Returns:
Type
Query
NameTypeDescription

queryableCodingKey (required)

EntryModel.FieldKeys

The member of your EntryModel.FieldKeys that you are performing your select operation against.

operation (required)

Query.Operation

The query operation used in the query.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .title, .equals("Entry Title"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .title, .notEquals("Entry Title"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .title, .includes(["one", "two"])
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .title, .excludes(["three", "four"]))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .age, .isLessThan(10))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .age, .isLessThanOrEqual(10))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .age, .isGreaterThan(10))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .age, .isGreaterThanOrEqual(10))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .title, exists(true))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: .title, .matches("^[a-z]"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

where(referenceAtKeyPath:_:)

Use this method to do a search on Entries which enables searching for entries based on value’s for members of referenced entries.

Returns:
Type
Query
NameTypeDescription

keyPath (required)

string

The reference field key path that you are performing your select operation against.

operation (required)

Query.Reference

The query operation used in the query.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
let referenceQuery = stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: EntryModel.FieldKeys.title,Query.Operation.equals("10"))
let inReference = Query.Reference.include(referenceQuery)
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(referenceAtKeyPath: .title, inReference)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
let referenceQuery = stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(queryableCodingKey: EntryModel.FieldKeys.title,Query.Operation.equals("10"))
let ninReference = Query.Reference.notInclude(referenceQuery)
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(referenceAtKeyPath: .title, ninReference)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

orderByAscending(propertyName:)

When fetching entries, you can sort them in the ascending order with respect to the value of a specific field in the response body.

Returns:
Type
Query
NameTypeDescription

propertyName (required)

string

The member of your `EntryModel.FieldKeys` that you are performing order by ascending.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.orderByAscending(propertyName: .title)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

orderByDecending(propertyName:)

When fetching entries, you can sort them in the descending order with respect to the value of a specific field in the response body.

Returns:
Type
Query
NameTypeDescription

propertyName (required)

string

The member of your `EntryModel.FieldKeys` that you are performing order by descending.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.orderByDecending(propertyName: .title)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

tags(for:)

Use this method to do a search on tags for Entries.

Returns:
Type
Query
NameTypeDescription

text (required)

string

The text string to match against.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.tags(for: "tagSearchString")
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

operator(_:)

Use this method to do a search on Entries which enables searching for entries based on Query.Operator.

Returns:
Type
Query
NameTypeDescription

operator (required)

Query.Operator

The member of Query.Operator that you are performing.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
let query1 = stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKeyPath: "title", Query.Operation.equals("Gold"))
let query2 = stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKeyPath: "name", Query.Operation.equals("John"))
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.operator(.and([query1, query2]))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
let query1 = stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKeyPath: "title", Query.Operation.equals("Gold"))
let query2 = stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.where(valueAtKeyPath: "name", Query.Operation.equals("John"))
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query()
.operator(.or([query1, query2]))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

EntryQueryable

Query class for Entry.

locale(_:)

Instance method to fetch Entry for specific locale.

Returns:
Type
Self
NameTypeDescription

locale (required)

string

The code for fetching entry for locale.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query()
.locale("<LOCALE_CODE>")
.fetch { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

only(fields:)

Specifies an array of only keys in BASE object that would be included in the response.

Returns:
Type
Self
NameTypeDescription

key (required)

[string]

List for field uids to included in response.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query()
.only(["<FIELD_UID_TO_EXCEPT>"])
.fetch { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

except(fields:)

Specifies an array of except keys in BASE object that would be included in the response.

Returns:
Type
Self
NameTypeDescription

key (required)

[string]

List for field uids to excepted in response

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query()
.except(["<FIELD_UID_TO_EXCEPT>"])
.fetch { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

includeReference(with:)

Instance method to include reference objects with given key in response.

Returns:
Type
Self
NameTypeDescription

key (required)

[string]

List for reference field uids to include reference in response.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query()
.includeReference(with: ["<REFERENCE_FIELD_UIDS>"])
.fetch { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

include(params:)

Instance method for including count, Unpublished, ContentType schema, Global Fields schema, and Reference ContentType Uid in result.

Returns:
Type
Self
NameTypeDescription

params (required)

Query.Include

The member of your Query.Include that you want to include in response

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query().include(params: [.count])

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query().include(params: [.refContentTypeUID])

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query().include(params: [.contentType])

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query().include(params: [.globalField])

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query().include(params: [.fallback])

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query().include(params: [.embeddedItems])

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query().include(params: [.
])

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query().include(params: [.count, .
])

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query().include(params: [.all])

includeReferenceField(with:only:)

Specifies an array of only keys in reference object that would be included in the response.

Returns:
Type
Self
NameTypeDescription

key (required)

string

Reference field uid as key to include reference.

fields

[String]

List of field uid's to be included in response.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query()
.includeReferenceField(with: "<REFERENCE_FIELD_UID>",only:["<ONLY_FIELD_UIDS>"])
.fetch { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

includeReferenceField(with:except:)

Specifies an array of except keys in reference object that would be included in the response.

Returns:
Type
Self
NameTypeDescription

key (required)

string

Reference field uid as key to include reference.

fields

[String]

List of field uid's to be excluded in response.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: contentTypeUID).entry().query()
.includeReferenceField(with: "<REFERENCE_FIELD_UID>",except:["<EXCEPT_FIELD_UIDS>"])
.fetch { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
   switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
   }
}

includeMetadata()

Includes AssetQuery metadata along with response body.

Returns:
Type
AssetQuery

let stack = Contentstack.stack(apiKey:"API_KEY", deliveryToken:"DELIVERY_TOKEN", environment: "ENVIRNOMENT")
stack.contentType(uid: contentTypeUID).entry().query()
.includeMetadata()
.fetch { (result: Result ContentstackResponse&lt;EntryMode&gt;, Error&lt;response: ResponseType&gt;) in
switch result {
case.success(let contentstackResponse):
case.failure(let error):
  }
}

FieldKeysQueryable

A protocol enabling strongly typed queries to the Contentstack Delivery API via the SDK.

NameTypeDescription

FieldKeys

CodingKey

The CodingKey representing the field identifiers/JSON keys for the corresponding content type. These coding keys should be the same as those used when implementing Decodable.

QueryProtocol

A base Query protocol which holds the essentials shared by all query types in the SDK which enable querying against content types, entries and assets.

NameTypeDescription

stack

Stack

The Stack instance to perform operation.

parameters

[String : Any]

The parameters dictionary that are converted to `URLComponents`.

queryParameter

[String : Any]

The Query parameters dictionary that are converted to `URLComponents`.

cachePolicy

CachePolicy

The cachePolicy that is use for fetching entity.

Queryable

The base Queryable protocol to find collections for content types, assets, and entries.

find(_:)

This is a generic find method which can be used to fetch collections of ContentType, Entry, and Asset instances.

Note: By default, the limit for response details per request is 100, with the maximum limit set at 250.

Returns:
Type
void
NameTypeDescription

completion (required)

ResultsHandler<ContentstackResponse<ResourceType>>

A handler which will be called on completion of the operation.

QueryableRange

Use types that conform to QueryableRange to perform queries with the four Range operators

NameTypeDescription

stringValue

String

A string representation of a query value that can be used in an API query.

ResourceQueryable

The base Queryable protocol to fetch instance for ContentType, Asset, and Entry.

fetch(_:)

This call fetches the latest version of a specific ContentType, Asset, and Entry of a particular stack.

Returns:
Type
void
NameTypeDescription

completion (required)

ResultsHandler<ResourceType>

A handler which will be called on completion of the operation.

Operator

When fetching entries, you can perform `and` or `or` operation.

NameTypeDescription

and([Query])

Operator

or([Query])

Operator

Reference

When fetching entries, you can search base on reference `$in` or `$nin`.

NameTypeDescription

include(Query)

Reference

notInclude(Query)

Reference

Operation

When fetching entries, you can search on field key paths.

NameTypeDescription

equals(QueryableRange)

Operation

notEquals(QueryableRange)

Operation

includes([QueryableRange])

Operation

excludes([QueryableRange])

Operation

isLessThan(QueryableRange)

Operation

isLessThanOrEqual(QueryableRange)

Operation

isGreaterThan(QueryableRange)

Operation

isGreaterThanOrEqual(QueryableRange)

Operation

exists(Bool)

Operation

matches(String)

Operation

Include

The `Query.Include` is parameter for including count, Unpublished, ContentType schema, Global Fields schema, and Reference ContentType Uid in result.

NameTypeDescription

rawValue

Int

Each bit of rawValue potentially represents an element of the option set.

count

Include

To include count in the response.

unpublished

Include

To include Unpublished Entries in response,

contentType

Include

To include ContentType schema in Entry response,



globalField

Include

To include Global Fields schema in Entry response.

refContentTypeUID

Include

To include Reference ContentType Uid in reference field in Entry response.

fallback

Include

Retrieve the published content of the fallback locale if an entry is not localized in specified locale.

embeddedItems

Include

Include Embedded Objects (Entries and Assets) along with entry/entries details.

all

Include

To include all Query.Include values.

QueryOn

To fetch all or find Entries and Querying for Specific Model use QueryOn.

where(queryableCodingKey:_:)

Use this method to do a search on Entries which enables searching for entries based on value’s queryable coding from `EntryType.FieldKeys`.

Returns:
Type
Query
NameTypeDescription

queryableCodingKey (required)

EntryType.FieldKeys

The member of your EntryType.FieldKeys that you are performing your select operation against.

operation (required)

Query.Operation

The query operation used in the query.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query(Product.Self)
.where(queryableCodingKey: .title, .equals("Entry Title"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
    switch result {
    case .success(let contentstackResponse):
        
    case .failure(let error):
        
    }
}

orderByAscending(propertyName:)

When fetching entries, you can sort them in the ascending order with respect to the value of a specific field in the response body.

Returns:
Type
Query
NameTypeDescription

propertyName (required)

EntryType.FieldKeys

The member of your EntryType.FieldKeys that you are performing order by ascending.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query(Product.Self)
.orderByAscending(propertyName: .title)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
    switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
    }
}

orderByDecending(propertyName:)

When fetching entries, you can sort them in the decending order with respect to the value of a specific field in the response body.

Returns:
Type
Query
NameTypeDescription

propertyName (required)

EntryType.FieldKeys

The member of your EntryType.FieldKeys that you are performing order by descending.

let stack = Contentstack.stack(apiKey: "<API_KEY>", deliveryToken: "<DELIVERY_TOKEN>", environment: "<ENVIRNOMENT>")
stack.contentType(uid: "<CONTENT_TYPE_UID>").entry().query(Product.Self)
.orderByDecending(propertyName: .title)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
    switch result {
    case .success(let contentstackResponse):
    case .failure(let error):
    }
}

Taxonomy

Taxonomy helps you categorize pieces of content within your stack to facilitate easy navigation and retrieval of information.

Taxonomy(stack:)

The Taxonomy(stack:) method initializes a new instance of the Taxonomy class.

Returns:
Type
Taxonomy
NameTypeDescription

stack (required)

Stack

The Stack instance for making API requests

Example:

let stack = Contentstack.stack( apiKey: "your_api_key", deliveryToken: "your_delivery_token", environment:"your_environment" ) 
let taxonomy = Taxonomy(stack: stack)

query()

The query() method creates a new Query instance for retrieving taxonomy entries.

Returns:
Type
Query

Example:

let stack = Contentstack.stack(apiKey: "api_key", deliveryToken: "delivery_token", environment: "environment") 
let taxonomy = Taxonomy(stack: stack) 
let query = taxonomy.query() 
query.where(valueAtKey: "taxonomies.test_taxonomy", .equals("test_term"))
query.limit(10)
query.skip(0)

fetch()

The fetch() method retrieves taxonomy data from Contentstack.

Returns:
Type
Result<TaxonomyModel, Error>

Example:

let stack = Contentstack.stack(apiKey: "api_key", deliveryToken: "delivery_token", environment: "environment") 
let taxonomy = Taxonomy(stack: stack)
let query = taxonomy.query() query.whereKey("title", .equals("Sample Taxonomy")) 
query.fetch { (result:Result<TaxonomyModel, Error>, response) in 
switch result { 
case .success(let taxonomyModel): print("Found taxonomy: \(taxonomyModel.title)") 
case .failure(let error): print("Query error: \(error.localizedDescription)")
 } 
}

where(valueAtKey:operation:)

The where(valueAtKey:operation:) method adds a constraint to the query.

Returns:
Type
Query
NameTypeDescription

valueAtKey

valueAtKey

The field key to query on

operation

Query.Operation

The operation to perform

Example:

let stack = Contentstack.stack(apiKey: "api_key", deliveryToken: "delivery_token", environment: "environment") 
let taxonomy = Taxonomy(stack: stack) 
let query = taxonomy.query()
query.where(valueAtKey: "taxonomies.test_taxonomy", .equals("test_term"))

operator()

The where(valueAtKey:operation:) method adds a constraint to the query.

Returns:
Type
Query
NameTypeDescription

operation

Query.LogicalOperation

The logical operation (.and/.or) with array of queries

Example:

let query1 = taxonomy.query().where(valueAtKey: "taxonomies.test_taxonomy", .equals("term1"))
let query2 = taxonomy.query().where(valueAtKey: "taxonomies.test_taxonomy", .equals("term2"))
query.operator(.or([query1, query2]))

Query Operations

Following are the available Query Operations:

Operations

Description

Example

.equals()

Performs an exact match.

.equals("test_term")

.includes()

Checks if the value exists in the array.

.includes(["term1", "term2"])

.below()

Matches terms below (excluding) the specified value.

.below("parent_term")

.eqBelow()

Matches terms below (including) the specified value.

.eqBelow("parent_term")

.above()

Matches terms above (excluding) the specified value.

.above("child_term")

.eqAbove()

Matches terms above (including) the specified value.

.eqAbove("child_term")

.or()

Combines queries using OR logic

.operator(.or([query1, query2]))

.and()

Combines queries using AND logic

.operator(.and([query1, query2]))