在同一子级Firebase中添加多个信息时遇到问题

时间:2019-01-23 13:37:29

标签: swift firebase

我想实现这一目标:

I want to achieve this

这是我当前的数据库。它仅显示1条信息,但应显示3条消息:

This is my current database, it only shows 1 information but it should be showing 3 messages

// loading the info onto firebase database
let uid = Auth.auth().currentUser?.uid
let ref = Database.database().reference()

ref.child("workout").observeSingleEvent(of: .value, with: { (snapshot) in
    print("Got Snapshot")
    print(snapshot.childrenCount)
    let chilidCount = snapshot.childrenCount
    print(chilidCount)
    let post:[String:String] = ["\(chilidCount + 1)": textField.text!]
    print(post)
    ref.child("workout").child(uid!).setValue(post)
})
self.tableView.reloadData()

到目前为止,这是我的代码。我尝试查看StackOverflow上的其他先前问题,也查看了Firebase文档,但找不到任何有用的东西。

这是我的表视图

this is my tableview

1 个答案:

答案 0 :(得分:0)

尝试制作一个要上载到FIR数据库的值的字典。

我假设您想将值上载到“锻炼”文件夹中的数据库中,并在该数据库中为每个用户上载值。您应该执行以下操作:

let uid = Auth.auth().currentUser?.uid
let ref = Database.database().reference()

//Reference to the location where the messages get saved to
let userWorkoutRef = ref.child("workout").child(uid!)

userWorkoutRef.observeSingleEvent(of: .value, with: { (snapshot) in
    // Get the number of messages
    let messagesCount = snapshot.childrenCount

//Making a dictionary: the key is the current number of messages plus one, the value is the current text entered in the text field
let valueToUpload = ["\(messagesCount + 1)": textField.text!]

//Uploading the dictionary to the database
userWorkoutRef.updateChildValues(valueToUpload) { (err, ref) in
    if err != nil {
        print(err!.localizedDescription)
        return
    } else {
        print("success uploading data to db!")
    }
}

}