我想要获取事件参与者列表,在事件节点中,只列出员工的ID号。我想实现的是从员工节点获取与该ID#关联的名称。这是我的dbase的结构。IOS Swift - 从Firebase数据库中的不同节点获取值
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(_发件人: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用户名:字符串,回调:@escaping(字符串) - >无效){
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)
}
}
})
}
不退还员工姓名。请帮忙。谢谢!
请在empName =(value [“name”]后面添加print(empName)as String)! getName函数中的语句来查看empName是否存在 – 3stud1ant3
您好,感谢您的回复。我确实尝试了它,并且它返回了名称,但它在打印名称后崩溃。它打印它,但不返回它 – TSM
请检查我的答案,看看它是否有帮助,如果您遇到问题,请在评论中提问 – 3stud1ant3