Global Fields

View as Markdown

Global Fields

A Global field is a reusable field, or group of fields, that you define once and use in several content types. Use the GlobalField class to

  • read one Global field and its schema by UID
  • list every Global field of the stack
  • add the _branch key or the Global field schema to the response

fetch(_:) and find(_:) decode each Global field into a GlobalFieldModel. The GlobalFieldModel, GlobalFieldDecodable and AnyDecodable sections below describe the model and its helper types.

Instance State

The Stack has two methods that return a GlobalField. The list below shows which methods work with and without a UID:

The SDK stops the app with a fatal error if you call fetch(_:) on a Global field without a UID, because fetch(_:) needs the UID. The compiler does not catch this.

Warning find(_:) ignores the UID. stack.globalField(uid: "GLOBAL_FIELD_UID").find lists every Global field of the stack, not the one you named. Use fetch(_:) to read one Global field.

Class-Level Notes

Settings stay on the object.

  • includeBranch() and includeGlobalFieldSchema() each store one query parameter on the Global field. fetch(_:) and find(_:) send every stored parameter, plus the environment of the stack, on every call.
  • No method removes a stored parameter. Call stack.globalField() again to send a request without it.

Headers.

  • GlobalField has no method that adds a header. fetch(_:) and find(_:) send only the headers of the Stack, such as the branch you passed to Contentstack.stack.

Caching.

  • cachePolicy is .networkOnly on every new Global field, whatever the Stack uses. Set it before you call fetch(_:) or find(_:).

Known issue createdAt and updatedAt of GlobalFieldModel are always nil, because the SDK decodes Global fields without its date format. To read the dates, decode created_at and updated_at as String in your own GlobalFieldDecodable type.

Capability Matrix

CapabilitySupportedNotes / Alternative
Filter, sort or page the Global field listNoGlobalField has no filter, limit or skip method
Send a custom header with one Global field requestNoSet the header for every request in httpAdditionalHeaders of the sessionConfiguration of ContentstackConfig
Read the creation and update datesNoSee the Known issue above

Class-Level Properties

PropertyTypeAccessDefaultDescription
cachePolicyCachePolicyRead-write.networkOnlyWhere fetch(_:) and find(_:) read the result from. The Stack page lists the values.
queryParameter[String: Any]Read-write[:]Conditions that find(_:) sends as the JSON query parameter when the dictionary is not empty. No GlobalField method writes to it.

GlobalFieldModel

GlobalFieldModel is the SDK's model for one Global field. Annotate the result of fetch(_:) as GlobalFieldModel, or the result of find(_:) as ContentstackResponse<GlobalFieldModel>. It is a final class that adopts GlobalFieldDecodable.

The table below lists its properties. Every property is public var.

PropertyTypeAccessDefaultDescription
uidStringRead-writeNot applicableUID of the Global field, from uid. Decoding fails without it.
titleStringRead-writeNot applicableTitle of the Global field, from title. Decoding fails without it.
descriptionString?Read-writenilDescription, from description.
createdAtDate?Read-writenilAlways nil. See the Known issue under Class-Level Notes.
updatedAtDate?Read-writenilAlways nil. See the Known issue under Class-Level Notes.
schema[[String: Any]]Read-write[]The fields of the Global field, one dictionary per field, from schema.
maintainRevisionsBool?Read-writenilValue of maintain_revisions.
inbuiltClassBool?Read-writenilValue of inbuilt_class.
versionInt?Read-writenilVersion number, from _version.
branchString?Read-writenilBranch UID, from _branch. The API returns the key when the request carries include_branch=true.
lastActivity[String: Any]Read-write[:]Value of last_activity.

FieldKeys. GlobalFieldModel.FieldKeys maps each property to its JSON key.

CaseRaw value
titletitle
uiduid
descriptiondescription
createdAtcreated_at
updatedAtupdated_at
maintainRevisionsmaintain_revisions
version_version
branch_branch
lastActivitylast_activity
inbuiltClassinbuilt_class
schemaschema

QueryableCodingKey. GlobalFieldModel.QueryableCodingKey has the cases uid, title, description, createdAt (created_at) and updatedAt (updated_at). No GlobalField method takes them.

GlobalFieldDecodable

GlobalFieldDecodable is the protocol for your own Global field model. A conforming type provides the following members:

  • the properties of GlobalFields: uid, title, createdAt, updatedAt, maintainRevisions, inbuiltClass, version and branch. The SystemFields page lists their types
  • a FieldKeys type that adopts CodingKey, from FieldKeysQueryable
  • a static endpoint that returns .globalfields, from EndpointAccessible
  • init(from:), from Decodable

AnyDecodable

AnyDecodable is a struct that decodes any JSON value. GlobalFieldModel uses it to read schema and last_activity. Its one property is value, of type Any. The decoder sets it to an Int, Double, Bool, String, array, dictionary or NSNull, and tries the types in that order.

Method Index

Method NameReturnsDescription
fetch(_:)Nothing. The completion handler receives the result.Reads one Global field by UID.
find(_:)Nothing. The completion handler receives the result.Lists every Global field of the stack.
includeBranch()The same Global field, for chaining.Adds the _branch key to the response.
includeGlobalFieldSchema()The same Global field, for chaining.Adds the Global field schema to the response.

Class-Level Snippet

The snippet below lists every Global field of the stack with its branch, then prints the UID and the number of fields of each.

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.globalField()
    .includeBranch()
    .find { (result: Result<ContentstackResponse<GlobalFieldModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let globalFields):
            for globalField in globalFields.items {
                print(globalField.uid, globalField.schema.count, globalField.branch ?? "main")
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Methods

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

fetch(_:)

fetch(_:) reads one Global field by UID and decodes it into the model type you name.

The async form, fetch() async throws -> ResourceType, does the same and returns the Global field directly. It needs iOS 13, macOS 10.15, tvOS 13 or watchOS 6.

NameTypeDescription
completion (required)@escaping (Result<ResourceType, Error>, ResponseType) -> Void

Receives the decoded Global field or the error, and the source of the result.

Default: Not applicable

ResourceType is the model you name in the closure annotation, usually GlobalFieldModel. It must adopt EndpointAccessible and Decodable.

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

The async form returns the requested Global field and throws on failure.

Validation

  • There is no client-side validation.
  • The SDK stops the app with a fatal error if the Global field has no UID, because fetch(_:) needs the UID to read one Global field. stack.globalField() without a UID creates such a Global field.
  • 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 Global field, 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/global_fields/{global_field_uid}, the Get a single global field request.
  • The request carries the environment of the Stack and the parameters that includeBranch() and includeGlobalFieldSchema() stored.
  • createdAt and updatedAt of the result are always nil. The Global Fields page explains the Known issue and the workaround.
  • The cachePolicy of the Global field selects whether fetch(_:) reads the network, the cache, or both. The async form serves .cacheThenNetwork as .cacheElseNetwork.

Example

Basic usage: read a Global field by UID

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.globalField(uid: "GLOBAL_FIELD_UID")
    .fetch { (result: Result<GlobalFieldModel, Error>, response: ResponseType) in
        switch result {
        case .success(let globalField):
            print(globalField.title, globalField.version ?? 0)
            for field in globalField.schema {
                print(field["uid"] ?? "", field["data_type"] ?? "")
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Use async/await

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let globalField: GlobalFieldModel = try await stack.globalField(uid: "GLOBAL_FIELD_UID").fetch()
    print(globalField.title, globalField.schema.count)
} catch {
    print(error)
}

find(_:)

find(_:) lists every Global field of the stack and decodes each one into the model type you name.

The async form, find() async throws -> ContentstackResponse<ResourceType>, does the same and returns the response directly. It needs iOS 13, macOS 10.15, tvOS 13 or watchOS 6.

NameTypeDescription
completion (required)@escaping ResultsHandler<ContentstackResponse<ResourceType>>

Receives the list or the error, and the source of the result.

Default: Not applicable

ResultsHandler<T> stands for (Result<T, Error>, ResponseType) -> Void. ResourceType is the model you name in the closure annotation, usually GlobalFieldModel.

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

The async form returns the Global fields of the stack and throws on failure.

Validation

  • There is no client-side validation.
  • When the API rejects the request, the result is .failure with an APIError (the async form throws it). Read errorCode, errorMessage and statusCode from it.

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

Behavior

  • find(_:) sends one GET request to /v3/global_fields, the Get all global fields request.
  • The request carries the environment of the Stack and the parameters that includeBranch() and includeGlobalFieldSchema() stored.
  • When the queryParameter property is not empty, find(_:) also sends it as the JSON query parameter.
  • find(_:) ignores the UID of the Global field, so it lists every Global field even on stack.globalField(uid:).
  • The ContentstackResponse holds the Global fields in items.

Example

Basic usage: list the Global fields of the stack

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.globalField()
    .find { (result: Result<ContentstackResponse<GlobalFieldModel>, Error>, response: ResponseType) in
        switch result {
        case .success(let globalFields):
            for globalField in globalFields.items {
                print(globalField.uid, globalField.title)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Use async/await

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
do {
    let globalFields: ContentstackResponse<GlobalFieldModel> = try await stack.globalField().find()
    print(globalFields.items.map { $0.uid })
} catch {
    print(error)
}

includeBranch()

includeBranch() asks the API to add the _branch key, the UID of the branch that holds the Global field, to the response.

This method takes no parameters.

Returns: GlobalField. The same Global field, for chaining.

Validation

  • There is no client-side validation.
  • Errors that do occur come from the fetch(_:) or find(_:) call that follows, not from includeBranch().

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

Behavior

  • Client-side only. includeBranch() stores include_branch=true on the Global field and makes no request. The fetch(_:) or find(_:) call that follows sends it.
  • The API then adds the _branch key to each Global field. See include_branch in Get all global fields.
  • The SDK reads _branch into the branch property of GlobalFieldModel. Without includeBranch(), branch is nil.
  • includeBranch() does not select the branch. The branch argument of Contentstack.stack selects it, as the example below shows.

Example

Basic usage: read a Global field with its branch

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT", branch: "BRANCH_UID")
stack.globalField(uid: "GLOBAL_FIELD_UID")
    .includeBranch()
    .fetch { (result: Result<GlobalFieldModel, Error>, response: ResponseType) in
        switch result {
        case .success(let globalField):
            print(globalField.title, globalField.branch ?? "No branch key")
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

includeGlobalFieldSchema()

includeGlobalFieldSchema() asks the API to include the schema of the Global field in the response.

This method takes no parameters.

Returns: GlobalField. The same Global field, for chaining.

Validation

  • There is no client-side validation.
  • Errors that do occur come from the fetch(_:) or find(_:) call that follows, not from includeGlobalFieldSchema().

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

Behavior

  • Client-side only. includeGlobalFieldSchema() stores include_global_field_schema=true on the Global field and makes no request. The fetch(_:) or find(_:) call that follows sends it.
  • The API then includes the schema of the Global field in the response. See include_global_field_schema in Get a single global field.
  • The SDK reads the schema into the schema property of GlobalFieldModel, one dictionary per field.
  • Calling includeGlobalFieldSchema() twice changes nothing, because both calls write the same value under the same key.

Example

Basic usage: read a Global field with its schema

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.globalField(uid: "GLOBAL_FIELD_UID")
    .includeGlobalFieldSchema()
    .fetch { (result: Result<GlobalFieldModel, Error>, response: ResponseType) in
        switch result {
        case .success(let globalField):
            for field in globalField.schema {
                print(field["uid"] ?? "", field["display_name"] ?? "")
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Both setters: list every Global field with its schema and branch

import ContentstackSwift

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.globalField()
    .includeGlobalFieldSchema()
    .includeBranch()
    .find { (result: Result<ContentstackResponse<GlobalFieldModel>, Error>, response: ResponseType) in
        guard case .success(let globalFields) = result else { return }
        for globalField in globalFields.items {
            print(globalField.uid, globalField.schema.count, globalField.branch ?? "")
        }
    }