如何获取存储在autoid生成的子节点中的数据?

时间:2017-10-29 09:18:06

标签: swift firebase

获取存储在swift中由autoid生成的子节点下的数据的最佳方法是什么。

firebase数据库的结构

 book007
    +---isbn                          //1st node
    +---user                          //2nd node
    +---userBooks                     //3rd node
        | --TikubNudhfiI90uNKIij        //3rd childnode  
        |    +-Thuimfim9876HUIhinn .   //3rd  childnode AutoGeneratedID
        |       --ThufdsfsYI7ihhuhGGU
        |            --BookIsbn:"23432423"     //need to get this node   
        |    +-ThuisddfsdUUHKIhinn 

代码未经优化我认为应该有更好的方法来实现。

   func fetchuser(){

        print("Fetching UserBooks!!")
        guard let uid = Auth.auth().currentUser?.uid else {
            print("No UID on fetchBook!!")
            return
        }

        Database.database().reference().child("userBooks").child(uid).observe(.childAdded, with: { (ChildKeysnapshot) in
            let partkey = ChildKeysnapshot.key
            print("partkey",partkey)

            // user > keys > all books (godeep = isbneach book)
         Database.database().reference().child("userBooks").child(uid).child(partkey).observeSingleEvent(of: .value, with: { (isbnShot) in

                if let DictIsbn = isbnShot.value as?[String:AnyObject]{

                    let isbnCell = BkCells()
                    isbnCell.setValuesForKeys(DictIsbn)
                    print("New updateISBN OF THIS USER",  isbnCell.bookISBN)
                    self.users.append(isbnCell)
                    print("IsbncellIS this",self.users.count)
                }

            print("This is Ron Before")
            self.fetchUserIsbn()

         }, withCancel: nil)

        }, withCancel: nil)
   }

1 个答案:

答案 0 :(得分:0)

您正在使用std::function事件观察用户的书籍,该事件将触发用户书籍节点下的每个孩子。闭包内返回的快照适用于每本书,因此无需再次请求书籍值。

childAdded

您应该对func fetchuser(){ guard let uid = Auth.auth().currentUser?.uid else { return } let ref = Database.database().reference(withPath: "userBooks/\(uid)") ref.observe(.childAdded, with: { snapshot in if let bookIsbn = snapshot.child("BookIsbn").value as? String { print(bookIsbn) } }, withCancel: nil) } 模型进行更改,以便可以通过BkCells对其进行初始化。

DataSnapshot

您可以为用户的import Firebase class BkCells: NSObject { var bookIsbn: String! init?(snapshot: DataSnapshot) { guard let bookIsbn = snapshot.child("BookIsbn").value as? String else { return nil } self.bookIsbn = bookIsbn } } 节点下的每个图书快照创建BkCell个实例。

userBooks