简体   繁体   中英

Retrieving Data From Firebase Auto Id's - Firebase Swift

I am wanting to capture all the values in my childByAutoId in firebase. Essentially, it stores all the items that a person has shortlisted. However, I do not seem to be capturing this, and I assume it is because I am not calling the snapshot correctly to factor the auto id's.

Database:

userID
 -> Favourited
    -> Auto Id
      -> itemName: x
    -> Auto Id
      -> itemName: x
    -> Auto Id
      -> itemName: x

Code:

func retrieveItems() {
        
  guard let userId = Auth.auth().currentUser?.uid else { return }

  let ref = Database.database().reference().child("users/\(userId)/Favourited")
        
   ref.observe(.value, with: { (snapshot) in
    if snapshot.childrenCount>0 {
       self.favUsers.removeAll()
       for likes in snapshot.children.allObjects as! [DataSnapshot] {
       let likesObject = likes.value as? [String: AnyObject]
       let itemName = likesObject!["itemName"]
       let likesList = Names(id: likes.key, itemName: itemName as! String?)
       self.favUsers.append(likesList)
  }
  } else {
    print("not yet")
  }
  })
    self.favList.reloadData()
  }

Could someone have a look and let me know what I may be doing wrong? Thank you!

This happens because Firebase loads data asynchronously, and right now you're calling reloadData before the self.favUsers.append(likesList) has ever run.

The call to reloadData needs to be inside the close/completion handler that is called when the data comes back from Firebase:

ref.observe(.value, with: { (snapshot) in
  if snapshot.childrenCount>0 {
     self.favUsers.removeAll()
     for likes in snapshot.children.allObjects as! [DataSnapshot] {
       let likesObject = likes.value as? [String: AnyObject]
       let itemName = likesObject!["itemName"]
       let likesList = Names(id: likes.key, itemName: itemName as! String?)
       self.favUsers.append(likesList)
    }
    self.favList.reloadData() // 👈 Move this here
  } else {
    print("not yet")
  }
})

I also recommend checking out some of these answers asynchronous data loading in Firebase .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM