Carlo Carlo - 1 month ago 16
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
refUsers.child(key).setValue(multipleBooksValues)

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
refUsers.child(key).child("multipleBooksNumber").setValue(values)
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

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]

        refUsers.child(key).child("multipleBooksNumber/\(bookNumber)").setValue(book.book_key!)

    }

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:

refUsers.child(key).child("multipleBooksNumber/\(book.book_key!)").setValue(true)

Or store them under so-called push IDs:

refUsers.child(key).child("multipleBooksNumber").childByAutoId().setValue(book.book_key!);
Comments