Ethan T Ethan T - 21 days ago 5
Swift Question

Accessing an array of data in Firebase using Swift?

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?

Answer

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