很抱歉,如果这是一个非常基本的问题,但我希望从一个Firebase表中获取userId并使用该userId从另一个Firebase表中提取数据。在第一个函数中,我调用fetchUserData函数来获取基于给定userid的用户的firstname。我能够提取名字,但是如何将它返回到我的第一个函数,以便我可以在append方法中插入它。
func fetchList() {
let currentUser = Auth.auth().currentUser!
let postRef = self.databaseRef.child("List").child(currentUser.uid)
postRef.observe(.value, with: { (snapshot) in
for childSnapshot in snapshot.children.allObjects as! [DataSnapshot] {
let userid = childSnapshot.key
self.fetchUserData(uid: userid)
self.userArray.append(User(firstname: "Need to get from fetchUserData", uid: userid))
self.tableView.reloadData()
}
})
}
func fetchUserData(uid: String){
let currentUserRef = databaseRef.child("users").child(uid)
currentUserRef.observeSingleEvent(of: .value, with: { (snapshot) in
//fetch firstname based on given uid
let value = snapshot.value as? NSDictionary
let firstname = value?["firstname"] as? String ?? ""
})
}
答案 0 :(得分:0)
您可以这样使用:
func fetchList() {
let currentUser = Auth.auth().currentUser!
let postRef = self.databaseRef.child("List").child(currentUser.uid)
postRef.observe(.value, with: { (snapshot) in
for childSnapshot in snapshot.children.allObjects as! [DataSnapshot] {
let userid = childSnapshot.key
self.fetchUserData(uid: userid, callback: { (firstName) in
self.userArray.append(User(firstname: firstName, uid: userid))
self.tableView.reloadData()
})
}
})
}
func fetchUserData(uid: String, callback: @escaping (_ firstname: String)->Void){
let currentUserRef = databaseRef.child("users").child(uid)
currentUserRef.observeSingleEvent(of: .value, with: { (snapshot) in
//fetch firstname based on given uid
let value = snapshot.value as? NSDictionary
let firstname = value?["firstname"] as? String ?? ""
callback(firstname)
})
}