获取用户信息并追加到数组 [英] Fetch User Info and append to an Array
本文介绍了获取用户信息并追加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很抱歉,如果这是一个非常基本的问题,但是我想从一个Firebase表中获取一个userId,并使用该userId从另一个Firebase表中提取数据.在第一个函数中,我调用fetchUserData函数根据给定的用户ID获取用户的名字.我可以提取名字,但是如何将其返回到我的第一个函数中,以便可以将其插入append方法中.
Sorry if this is a very basic question, but I'm looking to fetch a userId from one Firebase table and use that userId to pull data from another Firebase table. In the first function, I call a fetchUserData function to get the firstname of my user based on a given userid. I'm able to pull the firstname, but then how do I return it to my first function so that I can insert it in the append method.
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 ?? ""
})
}
推荐答案
您可以这样使用:
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)
})
}
这篇关于获取用户信息并追加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文