Asset
Asset
Assets are the media files uploaded to a stack, such as images, videos, PDFs and audio files. Use the Asset class to
- read one published asset by its UID
- add the image dimensions, the metadata, a relative URL or fallback-locale content to the response
- start an AssetQuery that lists or filters the assets of a stack
fetch(_:) decodes the asset into an AssetModel, or into your own type that adopts AssetDecodable. The AssetModel, ImageDimension and AssetDecodable sections below describe both.
Instance State
The asset(uid:) method of Stack is the only way to get an Asset. Which methods work depends on the uid argument:
- Call stack.asset(uid: "ASSET_UID") to read one asset. fetch(_:) and the setters, such as includeDimension(), apply to it.
- Call stack.asset() without a UID to list assets. Chain query() to get an AssetQuery, then call find on it.
The SDK stops the app with a fatal error if you call fetch(_:) on an asset without a UID, because fetch(_:) needs the UID to read one asset. The compiler does not catch this.
Warning The UID check tests only for nil. stack.asset(uid: "") passes it, and fetch(_:) then sends a request whose path ends in /assets/ with no UID. Nothing fails at the point of the mistake. Check that the UID variable is non-empty before you call asset(uid:).
Class-Level Notes
Settings stay on the object.
- locale(_:), includeRelativeURL(), includeFallback(), includeDimension() and includeMetadata() each store one query parameter on the asset and return the same asset.
- addValue(_:forHTTPHeaderField:) stores one header the same way.
- fetch(_:) sends every stored parameter and header plus the environment of the stack, and sends them again on each later call.
- No method removes a stored value. Call stack.asset(uid:) again to send a request without it.
What query() copies from the asset.
- query() copies only the UID, as a uid condition. The AssetQuery it returns starts with no parameters and no headers, and takes its cache policy from the Stack, not from the asset.
- Set the locale and the flags on the AssetQuery itself. Pass the locale code to its locale(_:) method, and pass .relativeURL, .fallback, .dimension or .metadata to its include(params:) method.
Caching.
- cachePolicy is .networkOnly on every new asset, whatever the Stack uses. Set it on the asset before you call fetch(_:). The cachePolicy Property section lists the values.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| List or filter the assets of a stack | Not on Asset | Call query() and then find on the AssetQuery |
| Read a specific version of an asset | No | The API accepts version, but Asset has no method that sends it |
| Add the _branch key to the response | No | Use an AssetQuery and send include_branch through the addURIParam(with:value:) method |
| Resize, crop or convert an image | No | Build the image URL with ImageTransform |
Class-Level Properties
| Property | Type | Access | Default | Description |
|---|---|---|---|---|
| cachePolicy | CachePolicy | Read-write | .networkOnly | Where fetch(_:) reads the asset from. See cachePolicy Property. |
AssetModel
AssetModel is the SDK's model for one asset. Annotate the result of fetch(_:) as AssetModel, or the result of find as ContentstackResponse<AssetModel>. AssetModel is a final class that adopts AssetDecodable.
The table below lists its properties. Every property is public var.
| Property | Type | Access | Default | Description |
|---|---|---|---|---|
| title | String | Read-write | Not applicable | Title of the asset, from title. Decoding fails without it. |
| uid | String | Read-write | Not applicable | UID of the asset, from uid. Decoding fails without it. |
| url | String | Read-write | Not applicable | URL of the file, from url. Decoding fails without it. |
| fileName | String | Read-write | Not applicable | File name, from filename. Decoding fails without it. |
| fileType | String | Read-write | Not applicable | MIME type, such as image/png, from content_type. Decoding fails without it. |
| fileSize | Double | Read-write | 0 | File size in bytes. The SDK converts the file_size string to a number, and keeps 0 when the key is missing or holds no number. |
| createdAt | Date? | Read-write | Not applicable | Creation time, from created_at. Decoding fails without the key, although the type is optional. |
| createdBy | String? | Read-write | Not applicable | UID of the user who created the asset, from created_by. Decoding fails without the key. |
| updatedAt | Date? | Read-write | Not applicable | Last update time, from updated_at. Decoding fails without the key. |
| updatedBy | String? | Read-write | Not applicable | UID of the user who last updated the asset, from updated_by. Decoding fails without the key. |
| dimension | AssetModel.ImageDimension? | Read-write | nil | Image height and width, from dimension. Filled only when the response has the key, for example after includeDimension(). |
| fields | [String: Any]? | Read-write | Every key of the asset object | Every key and value of the asset object in the response, including keys that have no typed property, such as tags and _metadata. |
toJSON(). toJSON() returns fields as a [String: Any] dictionary that JSONSerialization accepts. It converts any nested SDK model object to a plain dictionary and returns an empty dictionary when fields is nil.
FieldKeys. AssetModel.FieldKeys maps each typed property to its JSON key. The fetch(_:) decoder reads these keys.
| Case | Raw value |
|---|---|
| title | title |
| uid | uid |
| url | url |
| dimension | dimension |
| fileName | filename |
| fileType | content_type |
| fileSize | file_size |
| createdAt | created_at |
| createdBy | created_by |
| updatedAt | updated_at |
| updatedBy | updated_by |
QueryableCodingKey. AssetModel.QueryableCodingKey lists the keys you can pass to the where(queryableCodingKey:_:) method of AssetQuery.
| Case | Raw value |
|---|---|
| uid | uid |
| title | title |
| fileName | filename |
| createdAt | created_at |
| updatedAt | updated_at |
ImageDimension
AssetModel.ImageDimension is a struct with the width and height of an image asset. The API returns it for JPG, GIF, PNG, WebP, BMP, TIFF, SVG and PSD files when the request includes include_dimension=true. The Get a single asset API reference lists the supported image types.
The table below lists its properties.
| Property | Type | Access | Default | Description |
|---|---|---|---|---|
| width | Double? | Read-only | nil | Width of the image in pixels. nil when the key is missing or not a number. |
| height | Double? | Read-only | nil | Height of the image in pixels. nil when the key is missing or not a number. |
AssetDecodable
AssetDecodable is the protocol for your own asset model. Adopt it to decode assets into a type you define instead of AssetModel. A conforming type provides the following members:
- the properties of AssetFields: uid, title, createdAt, updatedAt, createdBy, updatedBy, fileName, fileSize, fileType and url. The SystemFields page gives their types
- a FieldKeys type that adopts CodingKey, from FieldKeysQueryable
- init(from:), from Decodable
The SDK supplies the endpoint. Every AssetDecodable type reads from the assets endpoint, so fetch(_:) and find accept it without more code.
Method Index
| Method Name | Returns | Description |
|---|---|---|
| locale(_:) | The same asset, for chaining. | Sets the locale of the asset to read. |
| includeFallback() | The same asset, for chaining. | Returns the fallback-locale asset when the locale has none published. |
| includeDimension() | The same asset, for chaining. | Adds the image height and width to the response. |
| includeMetadata() | The same asset, for chaining. | Adds the metadata of the asset to the response. |
| includeRelativeURL() | The same asset, for chaining. | Asks for the relative URL of the asset. |
| addValue(_:forHTTPHeaderField:) | The same asset, for chaining. | Adds a header to the fetch request. |
| fetch(_:) | Nothing. The completion handler receives the result. | Reads one published asset by its UID. |
| query() | A new asset query, limited to this asset when it has a UID. | Starts an AssetQuery to list or filter assets. |
| cachePolicy Property | The cache policy that fetch(_:) uses. | Chooses between the network and the cache for fetch(_:). |
Class-Level Snippet
The snippet below reads one image asset with its dimensions and metadata, then prints its file name, URL and size.
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
.includeDimension()
.includeMetadata()
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
switch result {
case .success(let asset):
print(asset.fileName, asset.url)
if let dimension = asset.dimension {
print("Width: \(dimension.width ?? 0), height: \(dimension.height ?? 0)")
}
print(asset.fields?["_metadata"] ?? "No metadata")
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Methods
Each method of the Asset class has its own section below, with its parameters, validation rules, behavior and examples.
addValue(_:forHTTPHeaderField:)
addValue(_:forHTTPHeaderField:) adds one HTTP header that fetch(_:) sends with the request for the asset.
| Name | Type | Description |
|---|---|---|
| value (required) | String | Header value. Sent as it is. |
| field (required) | String | Header name, such as branch. Names the header to send. |
Returns: Asset. The same asset, for chaining.
Validation
- There is no client-side validation. Empty strings reach the request as they are.
- Errors that do occur come from the fetch(_:) call that follows, not from addValue(_:forHTTPHeaderField:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. addValue(_:forHTTPHeaderField:) stores the header on the asset and makes no request. The fetch(_:) call that follows sends it, on top of the headers of the Stack.
- A second call with the same field replaces the stored value.
- A header you add here takes precedence over a header of the same name that the Stack sends, such as branch. The example below reads one asset from another branch this way.
- An added api_key or access_token value joins the value the SDK already sets on each request instead of replacing it. Do not use addValue(_:forHTTPHeaderField:) for those two headers.
- query() does not carry headers over to the AssetQuery. Add them there with the addValue(_:forHTTPHeaderField:) method of BaseQuery.
Example
Basic usage: read an asset from a specific branch
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
.addValue("BRANCH_UID", forHTTPHeaderField: "branch")
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
switch result {
case .success(let asset):
print(asset.title, asset.url)
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}cachePolicy Property
cachePolicy sets whether fetch(_:) reads the asset from the network, from the cache, or from both.
| Name | Type | Description |
|---|---|---|
| cachePolicy | CachePolicy | Source of the asset for fetch(_:). |
Returns: CachePolicy. The cache policy that fetch(_:) uses.
The table below lists the five values of CachePolicy. The Stack page describes the type.
| Value | Behavior of fetch(_:) |
|---|---|
| .networkOnly | Reads the network only. |
| .cacheOnly | Reads the cache only. A cache miss returns .failure with SDKError.cacheError. |
| .cacheElseNetwork | Reads the cache, and reads the network on a cache miss. |
| .networkElseCache | Reads the network, and reads the cache when the request fails or returns a status other than 200. |
| .cacheThenNetwork | Calls the completion handler twice, first with the cache and then with the network. On a cache miss, the first call receives .failure with SDKError.cacheError. |
Validation
- There is no client-side validation. The type system limits the value to the five cases.
- Errors that do occur come from the fetch(_:) call that follows, not from setting cachePolicy.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Every new asset starts with .networkOnly, whatever the cachePolicy of the Stack holds. Set it on the asset itself.
- The ResponseType argument of the completion handler is .cache or .network, so you can tell the two results of .cacheThenNetwork apart.
- The async form of fetch(_:) returns one value, so it serves .cacheThenNetwork as .cacheElseNetwork.
- query() does not carry the value over. An AssetQuery takes its policy from the Stack.
Example
Basic usage: show the cached asset first, then the fresh one
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let asset = stack.asset(uid: "ASSET_UID")
asset.cachePolicy = .cacheThenNetwork
asset.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
switch result {
case .success(let model):
print(response == .cache ? "Cached:" : "Network:", model.url)
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}fetch(_:)
fetch(_:) reads one published asset by its UID and decodes it into the model type you name.
The async form, fetch() async throws -> ResourceType, does the same and returns the asset directly. It needs iOS 13, macOS 10.15, tvOS 13 or watchOS 6.
| Name | Type | Description |
|---|---|---|
| completion (required) | @escaping (Result<ResourceType, Error>, ResponseType) -> Void | Receives the decoded asset or the error, and the source of the result. |
ResourceType is the model you name in the closure annotation, usually AssetModel. It must adopt EndpointAccessible and Decodable, as every AssetDecodable type does.
Returns: Void. Nothing. The completion handler receives the result.
The async form returns the requested asset and throws on failure.
Validation
- There is no client-side validation.
- The SDK stops the app with a fatal error if the asset has no UID, because fetch(_:) needs the UID to read one asset. stack.asset() without a UID creates such an asset.
- When the API rejects the request, the result is .failure with an APIError (the async form throws it). Read errorCode, errorMessage and statusCode from it.
- When the response holds no asset, the result is .failure with SDKError.invalidUID(string:), which carries the UID you passed.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- fetch(_:) sends one GET request to /v3/assets/{asset_uid}, the Get a single asset request.
- The request carries the environment of the Stack, every parameter that an earlier setter such as locale(_:) or includeDimension() stored, and every header that addValue(_:forHTTPHeaderField:) stored.
- The cachePolicy of the asset selects whether fetch(_:) reads the network, the cache, or both. With .cacheThenNetwork, the completion handler runs twice, and the ResponseType argument says which result arrived. The async form serves .cacheThenNetwork as .cacheElseNetwork.
Example
Basic usage: read an asset by UID
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
switch result {
case .success(let asset):
print(asset.fileName, asset.fileSize, asset.url)
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Offline fallback: read from the cache when the network fails
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let asset = stack.asset(uid: "ASSET_UID")
asset.cachePolicy = .networkElseCache
asset.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
guard case .success(let model) = result else { return }
print(model.url, response == .cache ? "from the cache" : "from the network")
}Use async/await
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
let asset: AssetModel = try await stack.asset(uid: "ASSET_UID").fetch()
print(asset.title, asset.url)
} catch {
print(error)
}includeDimension()
includeDimension() asks the API to add the height and width of an image asset to the response.
This method takes no parameters.
Returns: Asset. The same asset, for chaining.
Validation
- There is no client-side validation.
- Errors that do occur come from the fetch(_:) call that follows, not from includeDimension().
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. includeDimension() stores include_dimension=true on the asset and makes no request. The fetch(_:) call that follows sends it.
- The API returns the dimensions for JPG, GIF, PNG, WebP, BMP, TIFF, SVG and PSD files. See include_dimension in Get a single asset.
- The SDK decodes the dimension object into the dimension property of AssetModel, an ImageDimension with optional width and height. The ImageDimension section of the Asset class page describes the struct.
- dimension stays nil when the response has no dimension key, so check it for nil before you read it.
Example
Basic usage: read the size of an image
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
.includeDimension()
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
switch result {
case .success(let asset):
if let dimension = asset.dimension, let width = dimension.width, let height = dimension.height {
print("\(asset.fileName): \(width) x \(height)")
} else {
print("\(asset.fileName) has no dimensions")
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}includeFallback()
includeFallback() asks the API to return the asset from the fallback locale when the requested locale has no published version.
This method takes no parameters.
Returns: Asset. The same asset, for chaining.
Validation
- There is no client-side validation.
- Errors that do occur come from the fetch(_:) call that follows, not from includeFallback().
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. includeFallback() stores include_fallback=true on the asset and makes no request. The fetch(_:) call that follows sends it.
- The API then returns the published asset details from the fallback locale when the specified locale has none. See include_fallback in Get a single asset.
- Set the requested locale with locale(_:), as the example below does.
- Calling includeFallback() twice changes nothing, because both calls write the same value under the same key.
Example
Basic usage: read an asset with fallback-locale content
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
.locale("fr-fr")
.includeFallback()
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
switch result {
case .success(let asset):
print(asset.title, asset.url)
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}includeMetadata()
includeMetadata() asks the API to add the metadata of the asset to the response.
This method takes no parameters.
Returns: Asset. The same asset, for chaining.
Validation
- There is no client-side validation.
- Errors that do occur come from the fetch(_:) call that follows, not from includeMetadata().
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. includeMetadata() stores include_metadata=true on the asset and makes no request. The fetch(_:) call that follows sends it.
- The API returns the metadata under the _metadata key of the asset. See include_metadata in Get a single asset.
- AssetModel has no typed property for metadata. Read it from fields["_metadata"], as the example below does.
Example
Basic usage: read the metadata of an asset
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
.includeMetadata()
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
switch result {
case .success(let asset):
if let metadata = asset.fields?["_metadata"] as? [String: Any] {
print(metadata)
} else {
print("\(asset.title) has no metadata")
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}includeRelativeURL()
includeRelativeURL() asks the API for the relative URL of the asset instead of its full URL.
This method takes no parameters.
Returns: Asset. The same asset, for chaining.
Validation
- There is no client-side validation.
- Errors that do occur come from the fetch(_:) call that follows, not from includeRelativeURL().
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. includeRelativeURL() stores relative_urls=true on the asset and makes no request. The fetch(_:) call that follows sends it with Get a single asset.
- The SDK reads the url key into the url property of AssetModel as it is, without adding a host.
- Calling includeRelativeURL() twice changes nothing, because both calls write the same value under the same key.
Example
Basic usage: read the relative URL of an asset
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
.includeRelativeURL()
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
switch result {
case .success(let asset):
print(asset.url)
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}locale(_:)
locale(_:) sets the locale code that fetch(_:) sends with the request for the asset.
| Name | Type | Description |
|---|---|---|
| locale (required) | String | Locale code, such as "fr-fr". Selects the localized asset. |
Returns: Asset. The same asset, for chaining.
Validation
- There is no client-side validation. locale(_:) does not check the code, so an empty or unknown code reaches the API as it is.
- Errors that do occur come from the fetch(_:) call that follows, not from locale(_:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. locale(_:) stores the code under locale on the asset and makes no request.
- The fetch(_:) call that follows sends it as the locale query parameter of Get a single asset.
- A second call replaces the code from the first call.
- When the asset has no published version in that locale, add includeFallback() to get the version from the fallback locale.
- query() does not carry the locale over. Set it on the AssetQuery with its own locale(_:) method.
Example
Basic usage: read an asset in one locale
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset(uid: "ASSET_UID")
.locale("fr-fr")
.fetch { (result: Result<AssetModel, Error>, response: ResponseType) in
switch result {
case .success(let asset):
print(asset.title, asset.url)
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}query()
query() creates an AssetQuery that lists or filters the published assets of the stack.
This method takes no parameters.
Returns: AssetQuery. A new asset query, limited to this asset when it has a UID.
Validation
- There is no client-side validation. query() works on an asset with or without a UID.
- Errors that do occur come from the find call on the query, not from query().
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. query() makes no request. Call the find(_:) method on the query to send Get all assets.
- When the asset has a UID, query() adds a uid equals condition, so find returns at most that asset.
- The query does not carry over the parameters, headers or cache policy of the asset. It starts empty and takes its cachePolicy from the Stack.
- Each call returns a new query.
Example
Basic usage: list assets with a count
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
.include(params: .count)
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
switch result {
case .success(let assets):
print("\(assets.count ?? 0) assets")
for asset in assets.items {
print(asset.title, asset.url)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Filter assets by file name
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.asset().query()
.where(queryableCodingKey: .fileName, .matches("^banner"))
.find { (result: Result<ContentstackResponse<AssetModel>, Error>, response: ResponseType) in
guard case .success(let assets) = result else { return }
print(assets.items.map { $0.fileName })
}