• Stars
    star
    195
  • Rank 198,597 (Top 4 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A delightful Swift interface to Contentful's content delivery API.

header

Join Contentful Community Slack   Join Contentful Community Forum

contentful.swift - Swift Content Delivery Library for Contentful

Swift library for the Contentful Content Delivery API and Content Preview API. It helps you to easily access your Content stored in Contentful with your Swift applications.

This repository is actively maintained   MIT License   Build Status   Codebeat badge

Version   Carthage compatible   Swift Package Manager compatible   iOS | macOS | watchOS | tvOS  

What is Contentful?

Contentful provides content infrastructure for digital teams to power websites, apps, and devices. Unlike a CMS, Contentful was built to integrate with the modern software stack. It offers a central hub for structured content, powerful management and delivery APIs, and a customizable web app that enable developers and content creators to ship their products faster.

Table of contents

Core Features

Getting started

In order to get started with the Contentful Swift library you'll need not only to install it, but also to get credentials which will allow you to have access to your content in Contentful.

Installation

CocoaPods installation
platform :ios, '9.0'
use_frameworks!
pod 'Contentful'

You can specify a specific version of Contentful depending on your needs. To learn more about operators for dependency versioning within a Podfile, see the CocoaPods doc on the Podfile.

pod 'Contentful', '~> 5.0.0'

Carthage installation

You can also use Carthage for integration by adding the following to your Cartfile:

github "contentful/contentful.swift" ~> 5.0.0

Swift Package Manager [swift-tools-version 5.0]

Add the following line to your array of dependencies:

.package(url: "https://github.com/contentful/contentful.swift", .upToNextMajor(from: "5.0.0"))

Your first request

The following code snippet is the most basic one you can use to fetch content from Contentful with this library:

import Contentful

let client = Client(spaceId: "cfexampleapi",
                    environmentId: "master", // Defaults to "master" if omitted.
                    accessToken: "b4c0n73n7fu1")

client.fetch(Entry.self, id: "nyancat") { (result: Result<Entry, Error>) in
    switch result {
    case .success(let entry):
        print(entry)
    case .failure(let error):
        print("Error \(error)!")
    }
}

Accessing the Preview API

To access the Content Preview API, use your preview access token and set your client configuration to use preview as shown below.

let client = Client(spaceId: "cfexampleapi",
                    accessToken: "e5e8d4c5c122cf28fc1af3ff77d28bef78a3952957f15067bbc29f2f0dde0b50",
                    host: Host.preview) // Defaults to Host.delivery if omitted.

Authorization

Grab credentials for your Contentful space by navigating to the "APIs" section of the Contentful Web App. If you don't have access tokens for your app, create a new set for the Delivery and Preview APIs. Next, pass the id of your space and delivery access token into the initializer like so:

Map Contentful entries to Swift classes via EntryDecodable

The EntryDecodable protocol allows you to define a mapping between your content types and your Swift classes that entries will be serialized to. When using methods such as:

let query = QueryOn<Cat>.where(field: .color, .equals("gray"))

client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
    guard let cats = result.value?.items else { return }
    print(cats)
}

The asynchronously returned result will be an instance of ArrayResponse in which the generic type parameter is the same type you've passed into the fetch method. If you are using a Query that does not restrict the response to contain entries of one content type, you will use methods that return MixedArrayResponse instead of ArrayResponse. The EntryDecodable protocol extends the Decodable protocol in Swift 4's Foundation standard SDK. The library provides helper methods for resolving relationships between EntryDecodables and also for grabbing values from the fields container in the JSON for each resource.

In the example above, Cat is a type of our own definition conforming to EntryDecodable and FieldKeysQueryable. In order for the library to properly create your model types when receiving JSON, you must pass in these types to your Client instance:

let contentTypeClasses: [EntryDecodable.Type] = [
    Cat.self
    Dog.self,
    Human.self
]

let client = Client(spaceId: spaceId,
                    accessToken: deliveryAPIAccessToken,
                    contentTypeClasses: contentTypeClasses)

The source for the Cat model class is below; note the helper methods the library adds to Swift 4's Decoder type to simplify for parsing JSON returned by Contentful. You also need to pass in these types to your Client instance in order to use the fetch methods which take EntryDecodable type references:

final class Cat: EntryDecodable, FieldKeysQueryable {

    static let contentTypeId: String = "cat"

    // FlatResource members.
    let id: String
    let localeCode: String?
    let updatedAt: Date?
    let createdAt: Date?

    let color: String?
    let name: String?
    let lives: Int?
    let likes: [String]?
  
    // Metadata object if available
    let metadata: Metadata?

    // Relationship fields.
    var bestFriend: Cat?

    public required init(from decoder: Decoder) throws {
        let sys         = try decoder.sys()
        id              = sys.id
        localeCode      = sys.locale
        updatedAt       = sys.updatedAt
        createdAt       = sys.createdAt

        let fields      = try decoder.contentfulFieldsContainer(keyedBy: Cat.FieldKeys.self)
        self.metadata   = try decoder.metadata()
        self.name       = try fields.decodeIfPresent(String.self, forKey: .name)
        self.color      = try fields.decodeIfPresent(String.self, forKey: .color)
        self.likes      = try fields.decodeIfPresent(Array<String>.self, forKey: .likes)
        self.lives      = try fields.decodeIfPresent(Int.self, forKey: .lives)

        try fields.resolveLink(forKey: .bestFriend, decoder: decoder) { [weak self] linkedCat in
            self?.bestFriend = linkedCat as? Cat
        }
    }

    enum FieldKeys: String, CodingKey {
        case bestFriend
        case name, color, likes, lives
    }
}

If you want to simplify the implementation of an EntryDecodable, declare conformance to Resource and add let sys: Sys property to the class and assign via sys = try decoder.sys() during initialization. Then, id, localeCode, updatedAt, and createdAt are all provided via the sys property and don't need to be declared as class members. However, note that this style of implementation may make integration with local database frameworks like Realm and CoreData more cumbersome.

Optionally, decoder has a helper function to decode metadata.

Additionally, the library requires that instances of a type representing an entry or asset must be a class instance, not a struct—this is because the library ensures that the in-memory object graph is complete, but also that it has no duplicates.

Documentation & References

Reference Documentation

The library has 100% documentation coverage of all public variables, types, and functions. You can view the docs on the web or browse them in Xcode. For further information about the Content Delivery API, check out the Content Delivery API Reference Documentation.

Tutorials & other resources

  • This library is a wrapper around our Contentful Delivery REST API. Some more specific details such as search parameters and pagination are better explained on the REST API reference, and you can also get a better understanding of how the requests look under the hood.
  • Check the Contentful for Swift page for Tutorials, Demo Apps, and more information on other ways of using Swift with Contentful

Swift playground

If you'd like to try an interactive demo of the API via a Swift Playground, do the following:

git clone --recursive https://github.com/contentful/contentful.swift.git
cd contentful.swift
make open

Then build the "Contentful_macOS" scheme, open the playground file and go! Note: make sure the "Render Documentation" button is switched on in the Utilities menu on the right of Xcode, and also open up the console to see the outputs of the calls to print.

Example application

See the Swift iOS app on Github and follow the instructions on the README to get a copy of the space so you can see how changing content in Contentful affects the presentation of the app.

Migration

We gathered all information related to migrating from older versions of the library in our Migrations.md document.

Swift Versioning

It is recommended to use Swift 5.0, as older versions of the library will not have fixes backported. If you must use older Swift versions, see the compatible tags below.

Swift version Compatible Contentful tag
Swift 5.0 [ ≥ 5.0.0 ]
Swift 4.2 [ ≥ 4.0.0 ]
Swift 4.1 [2.0.0 - 3.1.2]
Swift 4.0 [0.10.0 - 1.0.1]
Swift 3.x [0.3.0 - 0.9.3]
Swift 2.3 0.2.3
Swift 2.2 0.2.1

Reach out to us

Have questions about how to use this library?

  • Reach out to our community forum: Contentful Community Forum
  • Jump into our community slack channel: Contentful Community Slack

You found a bug or want to propose a feature?

  • File an issue here on GitHub: File an issue. Make sure to remove any credential from your code before sharing it.

You need to share confidential information or have other questions?

  • File a support ticket at our Contentful Customer Support: File support ticket

Get involved

PRs Welcome

We appreciate any help on our repositories. For more details about how to contribute see our Contributing.md document.

License

This repository is published under the MIT license.

Code of Conduct

We want to provide a safe, inclusive, welcoming, and harassment-free space and experience for all participants, regardless of gender identity and expression, sexual orientation, disability, physical appearance, socioeconomic status, body size, ethnicity, nationality, level of experience, age, religion (or lack thereof), or other identity markers.

Read our full Code of Conduct.

More Repositories

1

contentful.js

JavaScript library for Contentful's Delivery API (node & browser)
TypeScript
1,174
star
2

rich-text

Libraries for handling and rendering Rich Text 📄
TypeScript
529
star
3

the-example-app.nodejs

Example app for Contentful in node.js
JavaScript
431
star
4

forma-36

A design system by Contentful
TypeScript
329
star
5

contentful-cli

The official Contentful command line interface. Use Contentful features straight from the command line!
JavaScript
322
star
6

contentful-migration

🚚 Migration tooling for contentful
TypeScript
320
star
7

contentful-management.js

JavaScript library for Contentful's Management API (node & browser)
TypeScript
264
star
8

extensions

Repository providing samples using the UI Extensions SDK
JavaScript
201
star
9

starter-gatsby-blog

Gatsby starter for a Contentful project from the community.
JavaScript
194
star
10

cf-graphql

Generate a GraphQL schema out of your Contentful space
JavaScript
185
star
11

blog-in-5-minutes

Vue
170
star
12

contentful-export

This tool allows you to export a Contentful space to a JSON dump
JavaScript
160
star
13

field-editors

React components and extensions for building Contentful entry editor
TypeScript
148
star
14

contentful_middleman

Contentful Middleman is an extension to use the Middleman static site generator (Ruby) together with the API-driven Contentful CMS.
Ruby
145
star
15

Stargate

A communication channel from your Mac to your watch.
Swift
135
star
16

contentful.rb

Ruby client for the Contentful Content Delivery API
Ruby
135
star
17

apps

Apps on the Contentful Marketplace and resources to build them
TypeScript
132
star
18

ui-extensions-sdk

A JavaScript library to develop custom apps for Contentful
TypeScript
120
star
19

discovery-app-react

A React.js based version of the Contentful Discovery app
JavaScript
111
star
20

contentful.php

Official PHP Library for the Content Delivery API
PHP
111
star
21

contentful-import

Node module that uses the data provided by contentful-export to import it to contentful space
TypeScript
99
star
22

jekyll-contentful-data-import

Contentful Plugin for the Jekyll Static Site Generator
Ruby
99
star
23

create-contentful-app

Bootstrap a Contentful App
TypeScript
98
star
24

gallery-app-react

A React application example for the gallery space template.
JavaScript
97
star
25

contentful.net

.NET Library for Contentful's Content Delivery and Management API
C#
95
star
26

template-blog-webapp-nextjs

Next.js blog starter template
TypeScript
89
star
27

contentful-metalsmith

A plugin for Metalsmith that pulls content from the Contentful API
JavaScript
86
star
28

vault

Easy persistence of Contentful data for Android over SQLite.
Java
84
star
29

template-marketing-webapp-nextjs

Next.js marketing website starter template
TypeScript
80
star
30

contentful.java

Java SDK for Contentful's Content Delivery API
Java
74
star
31

create-contentful-extension

Create Contentful Extension is a CLI tool for developing in-app extensions without the hassle of managing build configurations.
JavaScript
71
star
32

ContentfulWatchKitExample

Example for a WatchKit app using the Contentful SDK
Swift
71
star
33

gallery-app-android

Android application example for the gallery space template.
Java
68
star
34

template-ecommerce-webapp-nextjs

Next.js ecommerce website starter template
TypeScript
63
star
35

compose-starter-helpcenter-nextjs

A sample website frontend for Compose with Next.js
TypeScript
59
star
36

live-preview

Preview SDK for both the field tagging connection + live content updates
TypeScript
56
star
37

contentful_rails

A ruby gem to help you quickly integrate Contentful into your Rails site
Ruby
52
star
38

contentful.objc

Objective-C SDK for Contentful's Content Delivery API and Content Management API.
Objective-C
50
star
39

contentful-resolve-response

Resolve items & includes of a Contentful API response into a proper object graph
JavaScript
46
star
40

contentful.py

Python client for the Contentful Content Delivery API https://www.contentful.com/developers/documentation/content-delivery-api/
Python
45
star
41

contentful-laravel

Laravel integration for the Contentful SDK.
PHP
44
star
42

contentful_model

A lightweight wrapper around the Contentful api gem, to make it behave more like ActiveRecord
Ruby
44
star
43

contentful-space-sync

Synchronize Contentful spaces
JavaScript
42
star
44

the-example-app.swift

Example app for Contentful in Swift
Swift
42
star
45

covid-19-site-template

#project-covid19
JavaScript
40
star
46

11ty-contentful-starter

Contentful 11ty starter project.
CSS
39
star
47

contentful-management.py

Python client for the Contentful Content Management API https://www.contentful.com/developers/documentation/content-management-api/
Python
36
star
48

product-catalogue-js

Product catalogue in JavaScript
JavaScript
36
star
49

contentful-management.rb

Ruby client for the Contentful Content Management API
Ruby
33
star
50

ContentfulBundle

Symfony Bundle for the Contentful SDK.
PHP
32
star
51

contribution-program

Contribute to the Contentful blog with pieces on "better ways to build websites". Get rewarded for each post you publish.
30
star
52

contentful_express_tutorial

A Simple Express js application Built on top of Contentful
JavaScript
30
star
53

rich-text-renderer.swift

Render Contentful Rich Text fields to native strings and views
Swift
29
star
54

contentful_jekyll_examples

Examples for Contentful and Jekyll Integration
29
star
55

11ty-contentful-gallery

Photo Gallery made using Contentful and 11ty.
Liquid
28
star
56

guide-app-sw

A generic guide app for shop guides
JavaScript
27
star
57

ls-postman-rest-api

26
star
58

gallery-app-ios

An iOS application example for the gallery space template.
Swift
26
star
59

contentful-management.java

Java library for using the Contentful Content Management API
Java
26
star
60

contentful-bootstrap.rb

Contentful CLI tool for getting started with Contentful
Ruby
24
star
61

contentful-graphql-playground-app

Contentful App to integrate GraphQL Playground
TypeScript
23
star
62

wordpress-exporter.rb

Adapter to extract data from Wordpress
Ruby
23
star
63

contentful-database-importer.rb

Adapter to extract data from SQL Databases https://www.contentful.com
Ruby
23
star
64

blog-app-android

Android application example for the blog space template.
Java
22
star
65

contentful-sdk-core

Core modules for the Contentful JS SDKs
TypeScript
22
star
66

contentful-persistence.swift

Simplified persistence for the Contentful Swift Library.
Swift
21
star
67

content-models

A set of example content models build with and for Contentful
19
star
68

product-catalogue-android

Android application example for the product catalogue space template.
Java
19
star
69

the-example-app.graphql.js

Example app for Contentful with GraphQL with React
JavaScript
19
star
70

boilerplate-javascript

Boilerplate project for getting started using javascript with Contentful
JavaScript
19
star
71

the-example-app.php

Example app for Contentful in PHP
PHP
18
star
72

ng-contentful

Contentful module for AngularJS, providing access to the content delivery API
JavaScript
17
star
73

contentful_middleman_examples

A useful collection of examples using the `contentful_middleman` gem
Ruby
17
star
74

the-example-app.py

Example app for Contentful in Python
Python
17
star
75

The-Learning-Demo

Working repo for the new Learning Demo being developed by Learning Services
CSS
17
star
76

contentful-core.php

Foundation library for Contentful PHP SDKs
PHP
16
star
77

guide-app-ios

A generic iOS app for shop guides, styled as a guide to Coffee places.
Objective-C
16
star
78

starter-hydrogen-store

Example store starter template built with Contentful and Hydrogen framework from Shopify
JavaScript
16
star
79

contentful_django_tutorial

A Simple Django Application using Contentful
CSS
16
star
80

contentful-action

JavaScript
15
star
81

contentful-merge

CLI to merge entries between environments
TypeScript
15
star
82

contentful-batch-libs

Library modules used by contentful batch utility CLI tools.
JavaScript
15
star
83

sveltekit-starter

Starter repo to get started with Sveltekit and Contentful
Svelte
15
star
84

contentful-scheduler.rb

Scheduling Server for Contentful entries
Ruby
15
star
85

blog-app-ios

An iOS application example for the blog space template.
Swift
15
star
86

the-example-app.kotlin

The example Android app. See how to connect to a sample space and use kotlin and Contentful unisono.
Kotlin
15
star
87

contentful-social.rb

Contentful Social Publishing Gem
Ruby
14
star
88

discovery-app-android

Contentful Discovery App for Android
Java
14
star
89

discovery-app

iOS app for previewing the content of Contentful Spaces
Objective-C
14
star
90

ls-content-as-code

Example content migration API scripts
JavaScript
13
star
91

blog-app-laravel

Example app using Contentful with Laravel.
PHP
13
star
92

slash-developers

THIS REPOSITORY IS DEPRECATED. Please do not open new PRs or issues.
HTML
13
star
93

node-apps-toolkit

A collection of helpers and utilities for creating NodeJS Contentful Apps
TypeScript
12
star
94

rich-text.php

Utilities for the Contentful Rich Text
PHP
12
star
95

the-example-app.csharp

Example app for Contentful in C#
C#
12
star
96

the-example-app.graphql.swift

The Example App and Contentful GraphQL Endpoint, using Apollo iOS, Contentful/ImageOptions
Swift
12
star
97

contentful-link-cleaner

Cleans up unresolved Entry links in Contentful spaces
JavaScript
11
star
98

tvful

Example for using the Contentful SDK for tvOS apps.
Swift
11
star
99

contentful-sdk-jsdoc

JSDoc template and config for the Contentful JS SDKs
JavaScript
10
star
100

generator.java

Code generator for Contentful models
Shell
10
star