【发布时间】:2017-10-02 22:22:22
【问题描述】:
抱歉,这是一个非常基本的问题,但我希望从一个 Firebase 表中获取用户 ID,并使用该用户 ID 从另一个 Firebase 表中提取数据。在第一个函数中,我调用 fetchUserData 函数来根据给定的用户 ID 获取我的用户的名字。我可以提取名字,但是如何将它返回到我的第一个函数,以便我可以将它插入到 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 ?? ""
})
}
【问题讨论】:
-
这不起作用,因为它是一个侦听器,并且肯定不会完全返回/一次。只需将您的代码从
fetchUserData放入postRef.observe并将append放入currentUserRef.observe。
标签: swift firebase swift3 firebase-realtime-database