如何在不覆盖的情况下将数据写入Firebase

时间:2019-06-13 06:00:52

标签: swift firebase

let value = categoriessegment.titleForSegment(at: categoriessegment.selectedSegmentIndex)
let data = ["price":pricetextfield.text,"Discount":Discounttextfield.text,"Category":value,"Description":descriptiontextfield.text];
// ref.child(currentdate).setValue(data)
ref.child(currentdate).updateChildValues(data as [AnyHashable : Any])

1 个答案:

答案 0 :(得分:0)

Firebase SDK中无法仅添加数据(如果已存在),updateChildValues更新以前的值或插入新值。要检查数据是否已经存在,您首先需要获取以前的数据,然后您可以检查并做出决定。喜欢

   Database.database().reference().observeSingleEvent(of: DataEventType.value, with: { (snapshot) -> Void in
            if (snapshot.value != nil) {
                 // it means data already present
             } 
        })

我们还有另一个选择,允许/禁止通过Firebase规则覆盖数据,例如

{
  "rules": {    
    "your_node": {
        ".write": "data.exists()"   /// or ".write": "!data.exists()"  if you want to restrict overwrite
    }
  }
}