Swift 4的JSONDecoder可以与Firebase实时数据库一起使用吗?

我正在尝试解码Firebase DataSnapshot

中的数据,以便可以使用JSONDecoder对其进行解码.

当我使用URL通过网络请求(获取Data对象)访问它时,我可以正确解码此数据.

但是,我想使用Firebase API直接获取数据,使用0700所述的observeSingleEvent.

但是,当我这样做时,我似乎无法将结果转换为Data对象,我需要使用JSONDecoder.

是否可以使用DataSnapshot进行新的JSON解码?这怎么可能?我似乎无法弄明白.

不,Firebase会返回无法解码的FIRDataSnapshot.但是,您可以使用此结构,这非常简单易懂:

struct GroceryItem {

  let key: String
  let name: String
  let addedByUser: String
  let ref: FIRDatabaseReference?
  var completed: Bool

  init(name: String, addedByUser: String, completed: Bool, key: String = "") {
    self.key = key
    self.name = name
    self.addedByUser = addedByUser
    self.completed = completed
    self.ref = nil
  }

  init(snapshot: FIRDataSnapshot) {
    key = snapshot.key
    let snapshotValue = snapshot.value as! [String: AnyObject]
    name = snapshotValue["name"] as! String
    addedByUser = snapshotValue["addedByUser"] as! String
    completed = snapshotValue["completed"] as! Bool
    ref = snapshot.ref
  }

  func toAnyObject() -> Any {
    return [
      "name": name,
      "addedByUser": addedByUser,
      "completed": completed
    ]
  }

}

并使用toAnyObject()来保存您的项目:

let groceryItemRef = ref.child("items")

groceryItemRef.setValue(groceryItem.toAnyObject())

字体: https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2

翻译自:https://stackoverflow.com/questions/47464436/can-swift-4s-jsondecoder-be-used-with-firebase-realtime-database