2016-10-29 38 views
1

使用我的代碼我會保存多個數據在我的環中Firebase數據庫。我使用while循環來保存我的數據庫中的一些字符串,但我的應用程序只保存最後一本書,我不知道如何解決這個問題。有任何想法嗎?在FirebaseDatabase中使用循環保存多個數據 - Swift IOS

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 
       } 
      }) 

     } 

在此先感謝您。

回答

1

各下一本書在你的循環覆蓋以前的書。爲防止這種情況的最簡單方法是setValue()一個更深一層調用樹:雖然

while bookNumber < numberOfBooks { 

     let book = bookList[bookNumber] 

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

    } 

注意,火力地堡文檔和博客不推薦使用這樣的陣列來存儲數據。無論是存儲書籍自然項下:

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

或將它們存儲在所謂的推編號:

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

非常感謝:) – Carlo

0

也許問題是你將所有書籍保存到相同的路徑,並且他們一直被重寫,所以最後只保留最後一個。 您指定鍵一次

let key = refUsers.childByAutoId().key 

,然後將所有的值保存到路徑

refUsers.child(key).child("multipleBooksNumber").setValue(values) 
+0

我要救一個按鍵內的這些結果。我認爲問題出在循環中。 – Carlo