我的Firebase数据库已更新,而不是添加新项目

时间:2019-04-02 16:52:04

标签: swift firebase

我正在尝试使用此代码将一些数据保存到Firebase数据库,但是每次单击按钮保存时,我的数据都会更新,而不是将新项目添加到dtabase:

    @objc func handleButtonSalvar(){
    guard let title = titleTextfield.text else { return }
    guard let artist = artistTextField.text else { return }
    guard let label = labelTextField.text else { return }
    guard let vinylID = vinylIDTextField.text else { return }
    guard let vinylCountry = vinylCountryTextField.text else { return }
    guard let vinylLocation = vinylLocationTextField.text else { return }
    guard let vinylYear = vinylYearTextField.text else { return }
    let dictionary : [String : Any] = ["title" : title,"artist" : artist,"label" : label,"vinylID" : vinylID,"vinylCountry" : vinylCountry,"vinylLocation" : vinylLocation,"vinylYear" : vinylYear ]
    Database.database().reference().child("vinyls").setValue(dictionary) { (error, ref) in
        if let error = error {
            self.showMessage(alertTitle: "Error Saving to Database", messageToDisplay: "Something happened while saving your data.\(error.localizedDescription)")
            return
        }

        self.titleTextfield.text = ""
        self.artistTextField.text = ""
        self.labelTextField.text = ""
        self.vinylIDTextField.text = ""
        self.vinylCountryTextField.text = ""
        self.vinylLocationTextField.text = ""
        self.vinylYearTextField.text = ""
        self.buttonSalvar.isEnabled = false
        self.buttonSalvar.backgroundColor = UIColor(red: 50/255, green: 50/255, blue: 50/255, alpha: 0.4)
        self.showMessage(alertTitle: "Vinyl Saved", messageToDisplay: "Vinyl saved successfully!")
    }

我在做什么错了?

谢谢

2 个答案:

答案 0 :(得分:0)

您需要

Database.database().reference().child("vinyls").childByAutoId().setValue(dictionary)   { (err, ref) in

}

Database.database().reference().child("vinyls").child("newChildName").setValue(dictionary)   { (err, ref) in

}

答案 1 :(得分:0)

首先创建一个密钥。

guard let key = ref.child("posts").childByAutoId().key else { return }

然后将此键用作它的子级

Database.database().reference().child("vinyls/\(key)").setValue(dictionary)

希望有帮助!