DataSnapshotDecoder 1.0

DataSnapshotDecoder 1.0

MindSea Development Inc. 维护。



  • MindSea Development Inc.

DataSnapshotDecoder

使用 Swift 的 Decodable 与 Firebase 实时数据库的 DataSnapshot

假设您有

import Foundation

struct CoolData: Decodable {
    let hasBindle: Bool
    let interestingItemCount: Int
}

然后您可以通过以下方式获取您酷炫的数据列表

import FirebaseDatabase

let observer: DataSnapshot -> Void = { snapshot in
    let cools = try! DataSnapshotDecoder().decode([CoolData].self, from: snapshot)
    print("decoded cools! \(cools)")
}

Database.database().reference(withPath: "/cools").observe(.value, with: observer)

无需通过 JSON 进行往返或从 DataSnapshot 中手动提取值。直接从 Firebase 实时数据库享受到 Decodable 的所有好处。嵌套对象、数组、可选,应有尽有。

DataSnapshotDecoder 是对 Foundation.Decoder 进行非平凡但简单直观的自定义实现的一个示例。如果您正在导航该协议,这个示例可能很有帮助!

安装

使用 CocoaPods

由于我们依赖于静态框架 FirebaseDatabase,因此您需要 CocoaPods 1.4 或更高版本。

  1. pod 'DataSnapshotDecoder 添加到您的 Podfile 中。
  2. 执行 pod install

然后您需要在希望使用它的任何 .swift 文件中导入 import DataSnapshotDecoder

手动

假设您已经设置好了 FirebaseDatabase 框架

  1. 下载DataSnapshotDecoder.swift。 这是一个单独的“库”文件,所以这就是你需要的全部!
    • 或者如果你更喜欢,可以将此仓库作为 git 子模块(或等效的)添加。
  2. DataSnapshotDecoder.swift 拖到您的 Xcode 项目中。

贡献

问题和/或拉取请求都欢迎!也请随时给我们发电子邮件:[email protected]

有趣的事实

需要访问数据库对象的 key 和/或 priority 吗?没问题

struct CoolKeyedData: Decodable {
    let key: String
    let hasBindle: Bool
    let priority: String?
    
    private enum CodingKeys: String, CodingKey {
        case key = ".key"
        case hasBindle
        case priority = ".priority"
    }
}