我想获取一个事件的参与者列表,在事件节点中,只列出了该员工的id#。我想要实现的是从 Employee 节点获取与该id相关联的名称。这是我的dbase的结构。
events:
uuid:
name: summer festival 2017
site: vegas
participants:
employeeID1: true
employeeID2: true
Employee:
employeeID1:
name: gary
department: video production
这是我的代码
@IBAction func downloadButtonAction(_ sender: UIButton) {
ref.child("events").child(eventKeyLabel.text!).child("participants").observeSingleEvent(of: .value, with: {(snapshot) in
// get the dictionary from the snapshot
if let participantsDict = snapshot.value as? [String : AnyObject] {
for each in participantsDict {
let employeeIDNum = each.key
let employeeName = self.getName(forUID: employeeIDNum)
self.employeeID.append(employeeIDNum)
self.name.append(employeeName)
}
print(self.employeeID)
print(self.name)
}
}) // End observeSingleEvent
}
func getName(forUID userID: String) -> String{
var empName = ""
ref.child("Employee").child(userID).observe(DataEventType.value, with: { (snapshot) in
if let value = snapshot.value as? NSDictionary {
empName = (value["name"] as? String)!
}
})
return empName
}
结果:
["0001", "0002", "0003", "0004"]
["", "", "", ""]
完整代码:
@IBAction func downloadButtonAction(_ sender:UIButton){
ref.child("events").child(eventKeyLabel.text!).child("participants").observeSingleEvent(of: .value, with: {(snapshot) in
// get the dictionary from the snapshot
if let participantsDict = snapshot.value as? [String : AnyObject] {
for each in participantsDict {
let employeeIDNum = each.key
self.getName(forUID: employeeIDNum) { empName in
self.name.append(empName)
print(empName)
}
self.employeeID.append(employeeIDNum)
}
print(self.employeeID)
print(self.name)
}
}) // End observeSingleEvent
}
func getName(forUID userID:String,callback:@escaping(String) - > Void){
ref.child("Employee").child(userID).observe(DataEventType.value, with: { (snapshot) in
if let value = snapshot.value as? NSDictionary {
print(value)
if let empName = value["name"] as? String{
callback(empName)
}
}
})
}
它不会返回员工姓名。请帮忙。谢谢!
答案 0 :(得分:0)
问题是,因为从firebase获取是异步调用,所以你必须使用回调来获取调用getName方法的函数的名称,你可以这样做:
@IBAction func downloadButtonAction(_ sender: UIButton) {
ref.child("events").child(eventKeyLabel.text!).child("participants").observeSingleEvent(of: .value, with: {(snapshot) in
// get the dictionary from the snapshot
if let participantsDict = snapshot.value as? [String : AnyObject] {
for each in participantsDict {
let employeeIDNum = each.key
self.getName(forUID: employeeIDNum)
self.employeeID.append(employeeIDNum)
}
print(self.employeeID)
print(self.name)
}
}) // End observeSingleEvent
}
func getName(forUID userID: String) {
ref.child("Employee").child(userID).observe(DataEventType.value, with: { (snapshot) in
if let value = snapshot.value as? NSDictionary {
print(value) //add here
if let empName = value["name"] as? String{
self.name.append(empName)
}
}
})
}