Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

contentful/contentful.swift

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

header

Join Contentful Community Slack  Join Contentful Community Forum

contentful.swift - Swift Content Delivery Library for Contentful

Swift library for the ContentfulContent Delivery API andContent 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 theCocoaPods doc on the Podfile.

pod'Contentful','~> 5.0.0'

Carthage installation

You can also useCarthage for integration by adding the following to yourCartfile:

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 Contentfulletclient=Client(spaceId:"cfexampleapi",                    environmentId:"master", // Defaults to "master" if omitted.                    accessToken:"b4c0n73n7fu1")client.fetch(Entry.self, id:"nyancat"){(result:Result<Entry,Error>)inswitch 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.

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

Authorization

Grab credentials for your Contentful space bynavigating 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 viaEntryDecodable

TheEntryDecodable 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:

letquery= QueryOn<Cat>.where(field:.color,.equals("gray"))client.fetchArray(of:Cat.self, matching: query){(result:Result<ArrayResponse<Cat>>)inguardlet cats= result.value?.itemselse{return}print(cats)}

The asynchronously returned result will be an instance ofArrayResponse in which the generic type parameter is the same type you've passed into thefetch method. If you are using aQuery that does not restrict the response to contain entries of one content type, you will use methods that returnMixedArrayResponse instead ofArrayResponse. TheEntryDecodable protocol extends theDecodable protocol in Swift 4's Foundation standard SDK. The library provides helper methods for resolving relationships betweenEntryDecodables 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 toEntryDecodable andFieldKeysQueryable. In order for the library to properly create your model types when receiving JSON, you must pass in these types to yourClient instance:

letcontentTypeClasses:[EntryDecodable.Type]=[Cat.self    Dog.self,Human.self]letclient=Client(spaceId: spaceId,                    accessToken: deliveryAPIAccessToken,                    contentTypeClasses: contentTypeClasses)

The source for theCat model class is below; note the helper methods the library adds to Swift 4'sDecoder type to simplify for parsing JSON returned by Contentful. You also need to pass in these types to yourClient instance in order to use the fetch methods which takeEntryDecodable type references:

finalclassCat:EntryDecodable,FieldKeysQueryable{staticletcontentTypeId:String="cat"    // FlatResource members.letid:StringletlocaleCode:String?letupdatedAt:Date?letcreatedAt:Date?letcolor:String?letname:String?letlives:Int?letlikes:[String]?      // Metadata object if availableletmetadata:Metadata?    // Relationship fields.varbestFriend:Cat?publicrequiredinit(from decoder:Decoder)throws{letsys=try decoder.sys()        id= sys.id        localeCode= sys.locale        updatedAt= sys.updatedAt        createdAt= sys.createdAtletfields=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] linkedCatinself?.bestFriend= linkedCatas?Cat}}enumFieldKeys:String,CodingKey{case bestFriendcase name, color, likes, lives}}

If you want to simplify the implementation of anEntryDecodable, declare conformance toResource and addlet sys: Sys property to the class and assign viasys = try decoder.sys() during initialization. Then,id,localeCode,updatedAt, andcreatedAt are all provided via thesys 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 aclass instance, not astruct—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 theweb or browse them in Xcode. For further information about the Content Delivery API, check out theContent 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 theREST API reference, and you can also get a better understanding of how the requests look under the hood.
  • Check theContentful 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.gitcd contentful.swiftmake 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 toprint.

Example application

See theSwift 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 ourMigrations.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 versionCompatible 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.30.2.3
Swift 2.20.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 ourContributing.md document.

License

This repository is published under theMIT 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.


[8]ページ先頭

©2009-2025 Movatter.jp