0

I'm working on a Swift app using Firebase Database. I have a structure like this:

"Groups" : {
    "-KWewQiWc6QPfiq5X1AY" : {
      "Members" : [ "emmaturner", "maxturner", "ethanturner" ],
      "Teacher" : "ethanturner",
      "Title" : "Kimbra Followers",
      "groupId" : "-KWewQiWc6QPfiq5X1AY"
    }
}

I'm trying to access the data in Members, in order to see if the user is in that Group. I was previously using ref.child("Groups").queryOrdered(byChild: "Teacher").queryEqual(toValue: userId) However, I learned that this is only returning the group if the user is the Teacher. I tried "members/" and "members/0" in place of Teacher, but of course these either do not work or only return access for the first user. How can I get Firebase to return the group as long as their name is mentioned in the array of group members?

1 Answer 1

3

Try this:

var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
    var membersArray = [String]()


    ref.child("Groups").observeSingleEvent(of: .value, with: { (snapshot) in
        if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

            for snap in snapshots
            {
                let teacher = snap.childSnapshot(forPath: "Teacher").value as! String
                self.ref.child("Groups").child(snap.key).child("Members").observeSingleEvent(of: .value, with: { (member) in
                    if let members = member.children.allObjects as? [FIRDataSnapshot] {

                        for mem in members
                        {
                            print(mem.value as! String)
                            let currentMember = mem.value as! String
                            membersArray.append(currentMember)
                        }
                    }

                    if(membersArray.contains(teacher))
                    {
                        print(membersArray)
                    }
                })
            }
        }
    })
Sign up to request clarification or add additional context in comments.

6 Comments

This was working, but now I'm getting the error "Cannot cast NSNull to NSString" on let members = snap.childSnapshot ..., despite it being able to print the snapshot
And being able to print(members)
In firebase you have "Members": [ "emmaturner", "maxturner", "ethanturner" ] or "Members": 0:"emmaturner" 1:"maxturner" 2:"ethanturner". I'm asking beacause i tried add array as value and firebase automatically convert to 0: 1: 2:
you can try ? instead of !: snap.childSnapshot(forPath: "Members").value as? [String]
In Firebase I have 0: ethan turner, 1: max turner, 2: ethanturner
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.