-1

My database is laid out like below

users
  |
  @--uidABC
       |
       |---phone:"+13125550690"
       |
       |---followers
              |
              |----uid123
              |      |---timeStamp:111222
              |
              |----uid456
              |      |---timeStamp:777999

I use .observeSingleEvent to check to see if uidABC exists and if it does I want to check to see if there is a child named followers under that path.

I can use snapshot.hasChild("followers") to see if it's available and if it is how can I loop through all the children underneath snapshot.hasChild("...")?

I use the code below but it's looping through the wrong snapshot. It using the top level one when it should use whatever DataSnapshot is under followers

let ref = Database...child("users").child(uidABC)
ref.observeSingleEvent(of: .value, with: { (snapshot) in

    if !snapshot.exists() {

        // this user doesn't exist
        return
    }

    if !snapshot.hasChild("followers") {

       // this user exists but has no followers
       return
    }

    // this user exists and has followers now loop through them
    for uid in snapshot.children {

        let snapshot = uid as! DataSnapshot

        if let dict = snapshot.value as? [String:Any] {
            let timeStamp = dict["timeStamp"] as? Double
            // eg. check for a specific timeStamp
         }
     }
})
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256

2 Answers2

0

Use child:

// this user exists and has followers now loop through them
for uid in snapshot.childSnapshot("followers") {

    guard let snapshot = uid as! DataSnapshot else {
     // Followers error
    }

    if let dict = snapshot.value as? [String:Any] {
        let timeStamp = dict["timeStamp"] as? Double
        // eg. check for a specific timeStamp
     }
 }

You can find more here: Iterate over snapshot children in Firebase

excitedmicrobe
  • 2,338
  • 1
  • 14
  • 30
0

I got the answer from here and here

let ref = Database...child("users").child(uidABC)
ref.observeSingleEvent(of: .value, with: { (snapshot) in

    if !snapshot.exists() {

        // this user doesn't exist
        return
    }

    if !snapshot.hasChild("followers") {

        // this user exists but has no followers
        return
    }

    // this user exists and has followers now loop through them
    let childSnapshot = snapshot.childSnapshot(forPath: "followers") {

    for child in childSnapshot.children {

        let snap = child as! DataSnapshot

        let uid = snap.key

        if let dict = snap.value as? [String: Any] {

            let timeStamp = dict["timeStamp"] as? Double ?? 0
            // eg. check for a specific timeStamp
        }
    }
})
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256