Carlo Carlo - 1 year ago 80
Swift Question

Save multiple data with a loop in FirebaseDatabase - Swift IOS

with my code I would save multiple data with a loop in my Firebase Database. I have used a while loop to save some strings in my Database but my app saves only the last book and I don't know how to fix this problem. Any ideas?

let refUsers = FIRDatabase.database().reference().child("Users").child("User" + tag_login).child(user_key).child("Books").child("Others")
let key = refUsers.childByAutoId().key
let multipleBooksValues = ["multipleBooks": "Yes", "read": "Yes"] as NSDictionary

let refBooks = FIRDatabase.database().reference().child("Books").child("User's books").child(book_key)

var bookNumber = 0

let numberOfBooks = bookList.count

while bookNumber < numberOfBooks {

let book = bookList[bookNumber]

let values = ["book_key\(bookNumber)" : book.book_key!] as NSDictionary
refBooks.updateChildValues(["onGoingNegotiations" : "Yes", "other_user_key" : self.user_key, "other_tag_login": self.tag_login])

refUsers.child(key).child("multipleBooksNumber").observe(.value, with: { (snapshot) in
let numberChildren = Int(snapshot.childrenCount - 1)
if numberChildren == bookNumber{
bookNumber += 1


Thank you in advance.

Answer Source

Each next book in your loop is overwriting the previous book. The easiest way to prevent this is to call setValue() one level deeper in the tree:

    while bookNumber < numberOfBooks {

        let book = bookList[bookNumber]



Note though that the Firebase documentation and blog recommend against using arrays like this for storing data. Either store the books under their natural key:


Or store them under so-called push IDs:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download