gpt4 book ai didi

swift - firebase函数中的firebase函数

转载 作者:行者123 更新时间:2023-11-28 15:08:24 25 4
gpt4 key购买 nike

以下函数必须返回我所有用户的好友列表。但是,它只对其中一个 friend 这样做。我知道这是因为 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

最佳答案

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


}
}

})
}

关于swift - firebase函数中的firebase函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48064589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com