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

问题描述 投票:0回答:2

我正在尝试使用此代码将一些数据保存到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!")
    }

我究竟做错了什么?

谢谢

swift firebase
2个回答
0
投票

首先创建一个密钥。

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

然后使用此键作为它的孩子

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

希望能帮助到你!


0
投票

你需要

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

}

要么

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

}
© www.soinside.com 2019 - 2024. All rights reserved.