dre_84w934
dre_84w934

Reputation: 738

Firebase function in firebase function

The following function has to return all of my users's friends list. However it only does it for one of the friends. I know this is because the 2 firebase functions are running async, however I am not sure what I have to change the function so that it runs the way is should. That is retrieve all friends.

///retrieves all of user's friends
    func fetchFriends(completion: @escaping ([FriendModel])->()){
        FRIEND_REQ_REF.child(CURRENT_USER_ID).observe(.childAdded, with: {(snapshot) in
            var friends = [FriendModel]()
            if snapshot.value as? Int == 0 {
                self.USERS_REF.child(snapshot.key).observeSingleEvent(of: .value, with: {(snap) in
                    if let dictionary = snap.value as? [String : AnyObject]{
                        let friend = FriendModel()
                        friend.setValue(dictionary["userName"], forKey: "userName")
                        friend.setValue(dictionary["name"], forKey: "name")
                        friends.append(friend)
                        completion(friends)
                    }
                })
            }
        })
    }

this is my data structure:

FRIEND_REQ_REF
              firebaseUserID
                 friendFirebasegivenID : 0
                 anotherFriendFirebasegivenID : 0
USERS_REF
            friendFirebasegivenID
                 userName : String 
                 name : String 
            anotherFriendFirebasegivenID : 0
                 userName : String 
                 name : String 

Upvotes: 0

Views: 117

Answers (1)

rmickeyd
rmickeyd

Reputation: 1551

///retrieves all of user's friends
    func fetchFriends(completion: @escaping ([FriendModel])->()){
        FRIEND_REQ_REF.child(CURRENT_USER_ID).observe(.value, with: {(snapshot) in
            var friends = [FriendModel]()

            if let dict = snapshot.value as? [String : AnyObject] {
                for (_,k) in dict.enumerated() {

                    if k.value == 0 {

                        self.USERS_REF.child(k.key).observeSingleEvent(of: .value, with: {(snap) in
                    if let dictionary = snap.value as? [String : AnyObject]{
                        let friend = FriendModel()
                        friend.setValue(dictionary["userName"], forKey: "userName")
                        friend.setValue(dictionary["name"], forKey: "name")
                        friends.append(friend)
                        completion(friends)
                    }
                })
                    }


                }
            }

        })
    }

Upvotes: 1

Related Questions