使用 client.fetchArray 时出现内容错误

Contentful error when using client.fetchArray

我在尝试遵循 this 教程时遇到以下错误:

哦,没有出错:A response for the QueryOn<Thing> did return successfully, but a serious error occurred when decoding the array of Thing. Double check that you are passing Thing.self, and references to all other EntryDecodable classes into the Client initializer.

使用以下代码调用contentful时:

func fetch() {
    let query = QueryOn<Thing>.where(field: .description, .exists(true))

    client.fetchArray(of: Thing.self, matching: query) { (result: Result<ArrayResponse<Thing>>) in

        switch result {
        case .success(let things):
            guard let firstThing = things.items.first else { return }
            print(firstThing)
        case .error(let error):
            print("Oh no something went wrong: \(error)")
        }
    }
}

我的Thing模型是这样设置的:

我目前添加了两个 Things

我的东西 class 看起来像这样:

final class Thing: EntryDecodable, FieldKeysQueryable {

    enum FieldKeys: String, CodingKey {
        case name, description
    }

    static let contentTypeId: String = "thing"

    let id: String
    let localeCode: String?
    let updatedAt: Date?
    let createdAt: Date?

    let name: String
    let description: String

    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: Thing.FieldKeys.self)

        self.name  = try! fields.decodeIfPresent(String.self, forKey: .name)!
        self.description = try! fields.decodeIfPresent(String.self, forKey: .description)!
    }
}

谁能看到我遗漏了什么?

所以 Contentful 的文档无处不在。我遇到了同样的问题,但在检查了他们 GitHub 存储库 itself 中的文档后,我设法解决了这个问题。

基本上,您需要在客户端初始化方法中传递所有符合 'EntryDecodable' 和 'FieldKeysQueryable' 的 Swift 类。

希望对您有所帮助!

只是想让访问的人更容易。您需要做的就是确保您已将 contentTypeClasses 传递到客户端 Init 方法中。

https://github.com/contentful/contentful.swift#map-contentful-entries-to-swift-classes-via-entrydecodable

fileprivate let client = Client(spaceId: spaceKey, accessToken: contentDeliveryKey, contentTypeClasses: [YourCustomClass.self])
final class YourCustomClass: EntryDecodable, FieldKeysQueryable {
    static let contentTypeId: ContentTypeId = "yourCustomContentfulType"

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

感谢@Wazza 将 link 分享给 contentful 的 github 文档。