ContentfulPersistenceSwift 0.17.10

ContentfulPersistenceSwift 0.17.10

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布最新发布2024年4月
SPM支持SPM

Rouven WeßlingOlubukola MakinwaKhaled GarbayaTomasz SzulcMarius Kurgonas维护。



contentful-persistence.swift

Version Carthage compatible License Platform Build Status Coverage Status

这是一个将Contentful中的数据持久化到本地CoreData数据库的集成工具;基于官方Contentful Swift库构建。该库专门使用Content Delivery API的/sync端点来同步Contentful空间中的所有内容到设备。

什么是Contentful?

Contentful为数字团队提供了一个内容基础设施,用于为网站、应用程序和设备中的内容提供动力。与CMS不同,Contentful是为了与现代软件堆栈集成而构建的。它提供了一个中心化的结构化内容中心点,强大的管理和交付API,以及一个可定制的Web应用程序,使开发人员和内容创建者能够更快地交付数字产品。

开始使用

先决条件

在开始之前,强烈建议您熟悉 Apple 的 CoreData 框架,因为在开发过程中可能会遇到许多与 CoreData 相关的问题。请阅读CoreData 编程指南并查看其他(非内容式)示例。

用法

SynchronizationManager 管理您的 CoreData 数据库状态,并使其与 Contentful 空间的数据保持同步。

// Tell the library which of your `NSManagedObject` subclasses that conform to `EntryPersistable` should be used when mapping API resonses to CoreData entities.
let entryTypes = [Author.self, Category.self, Post.self]

// Initialize the data store and it's schema.
let store = CoreDataStore(context: self.managedObjectContext)
let persistenceModel = PersistenceModel(spaceType: SyncInfo.self, assetType: Asset.self, entryTypes: entryTypes)

// Initialize the Contentful.Client with a persistenceIntegration which will receive messages about changes when calling `sync methods`
self.client = Client(spaceId: "<YOUR_SPACE_ID>", accessToken: "<YOUR_ACCESS_TOKEN>")

// Create the manager.
self.syncManager = SynchronizationManager(client: self.client,
                                          localizationScheme: LocalizationScheme.all, // Save data for all locales your space supports.
                                          persistenceStore: self.store, 
                                          persistenceModel: persistenceModel)

// Sync with the API. 
self.syncManager.sync { _ in
  do {
    // Fetch all `Posts` from CoreData
    let post: Post? = try self.store.fetchAll(type: Post.self, predicate: NSPredicate(value: true))
  } catch {
    // Handle error thrown by CoreData fetches.
  }
}

定义您的 CoreData 模型

为了让您的模型类与 contentful-persistence.swift 一起工作,您需要让您的模型类遵循 AssetPersistable(用于 Contentful 资产)或 EntryPersistable(用于 Contentful 条目类型)。

然后您需要在项目中的相应模型文件 xcdatamodel 定义的模型中进行操作。两种类型的 EntryPersistableAssetPersistable 都必须有非可选的 id 属性,以及可选的 localeCodecreatedAtupdatedAt 属性。

注意:CoreData 实体的可选性与 Swift 的可选性有所不同。CoreData 实体的可选性表示在执行保存到数据库操作时,属性可能不存在。要配置属性的可选性,请打开 Xcode "工具"右侧侧栏中的"数据模型检查器"并切换"可选"复选框。

Contentful 字段到您数据模型实体的映射将自动推导,但您也可以通过在类上实现 static func mapping() -> [FieldName: String]? 来自定义它。

以下是一个模型类的示例。

import Foundation
import CoreData
import ContentfulPersistence
import Contentful

// The following @objc attribute is only necessary if your xcdatamodel Default configuration doesn't have your module
// name prepended to the Swift class. To enable removing the @objc attribute, change the Class for your entity to `ModuleName.Post`
@objc(Post) 
class Post: NSManagedObject, EntryPersistable {
      
    // The identifier of the corresponding Content Type in Contentful.
    static let contentTypeId = "post"

    // Properties of the `sys` object of Contentful resources.
    @NSManaged var id: String
    @NSManaged var localeCode: String?
    @NSManaged var createdAt: Date? 
    @NSManaged var updatedAt: Date?

    // Custom fields on the content type.
    @NSManaged var body: String?
    @NSManaged var comments: NSNumber?
    // NOTE: Unlike date fields in sys properties, this library can't store `Date` for custom fields.
    // Use `String` and map to date after fetching from CoreData
    @NSManaged var customDateField: String? 
    @NSManaged var date: Date?
    @NSManaged var slug: String?
    @NSManaged var tags: Data?
    @NSManaged var title: String?
    @NSManaged var authors: NSOrderedSet?
    @NSManaged var category: NSOrderedSet?
    @NSManaged var theFeaturedImage: Asset?

    // Define the mapping from the fields on your Contentful.Entry to your model class. 
    // In the below example, only the `title`, `date` and `author` fields and `featuredImage` link will be populated.
    static func fieldMapping() -> [FieldName: String] {
        return [
            "title": "title",
            "featuredImage": "theFeaturedImage",
            "author": "authors"
            "date": "date"
        ]    
    }
}

提示:对于基于 数组字段类型(如“短文本”、“列表”)的字段,请在数据模型中使用“二进制数据”类型,在 Swift 代码中使用“Data?”(例如 var tags: Data?)类型。要访问实际数组内容,使用 NSKeyedUnarchiver 解包“Data”字段,例如

extension Post {

    var theTags: [String]? {
        guard let tagsData = self.tags else { return nil }
        return NSKeyedUnarchiver.unarchiveObject(with: tagsData) as? [String]
    }
}

安装

CocoaPods 安装

CocoaPods 是Objective-C和Swift的依赖管理器,它自动化并简化了在你的项目中使用第三方库(如ContentfulPersistence)的过程。

platform :ios, '9.3'
use_frameworks!

target :MyApp do
  pod 'ContentfulPersistenceSwift', '~> 0.13.0'
end

Carthage 安装

您还可以通过将以下内容添加到您的 Cartfile 来使用 Carthage 进行集成。

github "contentful/contentful.swift" ~> 0.13.0

文档

有关更多信息,请参阅开发者文档或浏览API文档。后者也可以加载到Xcode作为Docset使用。

贡献和开发

要开始贡献,请克隆项目,然后在根目录下运行以下命令: make setup_env

make setup_env
carthage bootstrap --platform all

此命令将安装所有构建项目所需的开发依赖项,并执行测试。要从命令行运行测试,请执行 make test。测试也应该直接从Xcode应用程序中运行。

许可证

版权所有 (c) 2018 Contentful GmbH。有关详细信息,请参阅LICENSE