我试图将我从firebase数据库中检索到的数据传递到我的单身人士的字段中。数据是通过闭包接收的,在那个闭包中我将一些数据传递给我的单例属性。如果我在封闭内部打印数据结构(在分配了所有内容之后),我得到了我期待的输出,但是如果我在初始化程序结束时打印出所有数据应该是&#39传入后,它是空的。
import Foundation
import Firebase
class EmployeeList {
static let sharedInstance = EmployeeList()
var employeeDictionary: [String: [EmployeeData]]
var ref: DatabaseReference!
private init() {
employeeDictionary = [String: [EmployeeData]]()
ref = Database.database().reference()
ref.child("employeeList").observeSingleEvent(of: .value, with: { snapshot in
if let dictionary = snapshot.value as? [String: [String: AnyObject]] {
for subsection in dictionary {
var subsectionEmployees: [EmployeeData] = []
for item in subsection.value {
self.ref.child("employeeList/\(subsection.key)/\(item.key)").observeSingleEvent(of: .value, with: { employeeSnapshot in
let employeeObject = EmployeeData(snapshot: employeeSnapshot)
subsectionEmployees.append(employeeObject)
self.employeeDictionary[subsection.key] = subsectionEmployees
//print(self.employeeDictionary) This print statement prints out the expected data every time another employee is appended
})
}
}
}
//print(self.employeeDictionary) This print statement prints an empty data structure
})
}
}
答案 0 :(得分:0)
从Firebase获取数据如下
var messagedata = [String:AnyObject]()
let databaseReff = Database.database().reference().child("message")
databaseReff.queryOrdered(byChild: "fromId").queryEqual(toValue: self.recieverId).observe(.value, with: { snapshot in
if snapshot.exists(){
self.messagedata = snapshot.value! as! [String : AnyObject]
self.getAllMessagesSent(snapshot: self.messagedata)
} else
self.getAllMessagesSent(snapshot: self.messagedata) //Function Created
}
})
将从Clousre获取的数据传递给字典并将该dict传递给函数并执行任何您想要执行的操作或使用转义块
func getAllMessagesSent(snapshot: [String:AnyObject]) {
//data is here
}