Ethan T Ethan T - 1 year ago 72
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
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download