Firebase功能中的Firebase功能

问题描述 投票:0回答:1

以下函数必须返回我所有用户的好友列表。然而它只为其中一个朋友做到了。我知道这是因为2个firebase函数正在运行异步,但是我不知道我必须更改函数以便它运行的方式应该是。那是检索所有朋友。

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

这是我的数据结构:

FRIEND_REQ_REF
              firebaseUserID
                 friendFirebasegivenID : 0
                 anotherFriendFirebasegivenID : 0
USERS_REF
            friendFirebasegivenID
                 userName : String 
                 name : String 
            anotherFriendFirebasegivenID : 0
                 userName : String 
                 name : String 
swift firebase asynchronous firebase-realtime-database data-synchronization
1个回答
1
投票
///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)
                    }
                })
                    }


                }
            }

        })
    }
© www.soinside.com 2019 - 2024. All rights reserved.