Contentstack Delivery Objective C SDK

View as Markdown

Overview

This reference covers the public API of the Contentstack CocoaPods package, the Objective-C Content Delivery SDK, one page per class. Use it to look up parameters, return types, validation behavior, and Objective-C and Swift examples for every method you reach from #import <Contentstack/Contentstack.h>.

Before you begin This reference assumes you have installed and initialized the SDK. If you have not, complete the Get Started with iOS SDK guide first. This SDK requires iOS 12.0 or later. This reference documents version 3.16.1, and the changelog lists behavior changes between releases.

Note This SDK is in maintenance. Contentstack fixes critical issues only and adds no new features. For a new iOS project, use the Swift Delivery SDK, which you add with Swift Package Manager. Apps already built on this SDK continue to run with it.

Minimum Working Example

This snippet creates a stack, fetches one entry, and prints its title or the error the API returned.

#import <Contentstack/Contentstack.h>

Stack *stack = [Contentstack stackWithAPIKey:@"API_KEY" accessToken:@"DELIVERY_TOKEN" environmentName:@"ENVIRONMENT"];
Entry *entry = [[stack contentTypeWithName:@"CONTENT_TYPE_UID"] entryWithUID:@"ENTRY_UID"];
[entry fetch:^(ResponseType type, NSError *error) {
    if (error) {
        NSLog(@"Error %ld: %@", (long)error.code, error.userInfo[@"error_message"]);
        return;
    }
    NSLog(@"%@", entry.title);
}];

The same call in Swift:

import Contentstack

let stack = Contentstack.stack(withAPIKey: "API_KEY", accessToken: "DELIVERY_TOKEN", environmentName: "ENVIRONMENT")
let entry = stack.contentType(withName: "CONTENT_TYPE_UID").entry(withUID: "ENTRY_UID")
entry.fetch { (type, error) in
    if let error = error as NSError? {
        print("Error \(error.code): \(error.userInfo["error_message"] ?? "")")
        return
    }
    print(entry.title)
}

SDK Structure

Every object that reads content comes from a Stack. Factory methods such as contentTypeWithName:, entryWithUID:, query and assetLibrary make no request. Setter methods such as includeCount or whereKey:equalTo: return nothing and store the setting on the object. A send method makes the request. Use fetch: for one entry, asset or global field, find: and findOne: for a query, fetchAll: for the asset library, and the sync methods on Stack.

Because setters only store a value, a value the API rejects surfaces in the error argument of the next send method's completion block, not where you passed it.

Class Overview

Start and configure. The table below lists the classes that create a stack and configure its requests.

ClassRoleAccessed via
ContentstackEntry point that creates a stack and cancels its requests.[Contentstack stackWithAPIKey:accessToken:environmentName:]
ConfigRegion, host, branch, early access and TLS settings for a stack.[[Config alloc] init]
StackOne stack and one environment, and the factory for every other object.[Contentstack stackWithAPIKey:accessToken:environmentName:config:]

Content. The table below lists the classes that read content from a stack.

ClassRoleAccessed via
ContentTypeOne content type and its schema.[stack contentTypeWithName:]
EntryOne entry of a content type.[contentType entryWithUID:]
GroupA Group field value inside an entry.[entry groupForKey:]
QueryFilters, sorts and pages entries of a content type or a taxonomy search.[contentType query]
QueryResultThe response of one query request.find: completion block
TaxonomySearches entries by taxonomy terms.[stack taxonomy]
GlobalFieldOne global field or the list of global fields.[stack globalFieldWithName:]

Assets. The table below lists the classes that read assets.

ClassRoleAccessed via
AssetOne asset.[stack assetWithUID:]
AssetLibraryLists and filters assets.[stack assetLibrary]

Sync and enumerations. The table below lists the sync result class and the enumerations that list the values of a property or an argument.

ClassRoleAccessed via
SyncStackThe result of one sync request, with its items and tokens.sync: completion block
CachePolicyValues for the cachePolicy property of an entry, query, asset, asset library or global field.entry.cachePolicy
ResponseTypeWhether a completion block received network or cached data.First argument of a completion block
ContentstackRegionValues for the region of a stack.config.region
PublishTypeValues that filter a sync by publish event.[stack syncPublishType:completion:]
OrderBySort direction for the asset library.[assetLibrary sortWithKey:orderBy:]

Task Index

TaskStart hereClass
Fetch one entry by UIDfetch:Entry
Include referenced entries in an entryincludeRefFieldWithKey:Entry
Filter entries by a field valuewhereKey:equalTo:Query
Page through a large resultlimitObjects:Query
Get entries in another locale with fallbackincludeFallbackQuery
Find entries tagged with a taxonomy termfindTaxonomy:Query
List assetsfetchAll:AssetLibrary
Resize or reformat an imageimageTransformWithUrl:andParams:Stack
Fetch a global field schemafetch:GlobalField
Sync all published contentsync:Stack
Get only changes since the last syncsyncToken:completion:Stack
Target a region or branchConfigConfig

Key Usage Patterns

These examples assume a stack created as in the Minimum Working Example.

Fetch an entry and resolve its references

Entry *entry = [[stack contentTypeWithName:@"blog_post"] entryWithUID:@"ENTRY_UID"];
[entry includeRefFieldWithKey:@[@"author"]];
[entry fetch:^(ResponseType type, NSError *error) {
    if (error) { return; }
    NSLog(@"%@", [entry objectForKey:@"author"]);
}];
let entry = stack.contentType(withName: "blog_post").entry(withUID: "ENTRY_UID")
entry.includeRefField(withKey: ["author"])
entry.fetch { (type, error) in
    guard error == nil else { return }
    print(entry.object(forKey: "author") ?? "")
}

Filter and page a query

Query *query = [[stack contentTypeWithName:@"blog_post"] query];
[query whereKey:@"category" equalTo:@"news"];
[query orderByDescending:@"updated_at"];
[query limitObjects:@(20)];
[query skipObjects:@(20)];
[query find:^(ResponseType type, QueryResult *result, NSError *error) {
    if (error) { return; }
    for (Entry *entry in [result getResult]) {
        NSLog(@"%@", entry.title);
    }
}];
let query = stack.contentType(withName: "blog_post").query()
query.whereKey("category", equalTo: "news")
query.order(byDescending: "updated_at")
query.limitObjects(20)
query.skipObjects(20)
query.find { (type, result, error) in
    guard error == nil else { return }
    for entry in result?.getResult() ?? [] {
        print(entry.title)
    }
}

Sync published content, then fetch only changes

[stack sync:^(SyncStack *syncResult, NSError *error) {
    if (error) { return; }
    NSLog(@"%lu items", (unsigned long)syncResult.items.count);
    if (syncResult.syncToken) {
        [stack syncToken:syncResult.syncToken completion:^(SyncStack *changes, NSError *error) {
            if (error) { return; }
            NSLog(@"%lu changed items", (unsigned long)changes.items.count);
        }];
    }
}];
stack.sync { (syncResult, error) in
    guard error == nil, let syncResult = syncResult else { return }
    print("\(syncResult.items?.count ?? 0) items")
    if let token = syncResult.syncToken {
        stack.syncToken(token) { (changes, error) in
            guard error == nil, let changes = changes else { return }
            print("\(changes.items?.count ?? 0) changed items")
        }
    }
}

SDK-Wide Notes

ConcernBehaviorDefault when unset
AuthenticationThe stack sends the API key and delivery token as the api_key and access_token headers of every request, and the environment with every fetch and find. The SDK checks none of the three before the first request.Not applicable, the constructor takes all three.
Regions and endpointsThe SDK sends every request to the US host unless you set region on a Config and pass it to stackWithAPIKey:accessToken:environmentName:config:. Setting host directly targets a custom host, and ContentstackRegion lists the region values.US, host cdn.contentstack.io.
BranchesSet branch on the Config. Every request of the stack then sends the branch header.No header, so the API uses the main branch.
Rate limiting and retryThis SDK automatically retries on 408 and 429, up to 5 times, with delays of 0.2, 0.4, 0.8, 1.6 and 3.2 seconds. No setting changes the limit or the delays.Always on.
ErrorsWhen the API rejects a request, the completion block receives an NSError whose code is the HTTP status and whose userInfo holds error_message, error_code and errors. A connection failure comes from NSURLErrorDomain.Not applicable.
Completion blocksCompletion blocks run on a background queue. Dispatch to the main queue before you update UI.Not applicable.
CachingSet cachePolicy on an entry, query, asset, asset library or global field. See CachePolicy.NETWORK_ONLY.

Warning This SDK requires a delivery token. A management token or a preview token returns error code 109, "We can't find that Stack", which does not report that the token type is wrong. Create a delivery token under Settings, Tokens in your stack.

SDK Limitations

CapabilitySupportedNotes / Alternative
Read cached data with CACHE_ONLY, CACHE_ELSE_NETWORK or CACHE_THEN_NETWORKNoThese policies send a network request and never read the cache. Use NETWORK_ELSE_CACHE to fall back to cached data when a request fails.
Install with Swift Package ManagerNoThe SDK ships through CocoaPods only. For Swift Package Manager, use the Swift Delivery SDK.