我想要獲取事件參與者列表,在事件節點中,只列出員工的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