如何将数据传递到从Firebase检索信息的闭包之外? [英] How to pass data out of a closure that retrieves info from Firebase?
问题描述
我正在尝试将从Firebase数据库中检索到的数据传递到我的单例字段中.数据是通过闭包接收的,在该闭包中,我正在将一些数据传递到我的单例属性中.如果我在闭包内部打印数据结构(在分配完所有内容之后),则会得到期望的输出,但是如果在所有数据都应传递之后在初始化程序的末尾打印它,则该输出为空.
I'm trying to pass data that I've retrieved from my firebase database into a field of my singleton. The data is received via closure, and in that closure I'm passing some data into my singleton's properties. If I print the data structure inside the closure (after everything's been assigned) I get the output I'm expecting, but if I print it at the end of the initializer after all the data should've been passed in, it's empty.
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
})
}
}
推荐答案
从Firebase如下获取数据
get data from Firebase as Below
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提取的数据传递给字典,并将该字典传递给函数,并执行您想做的任何事情或使用转义块
pass the data fetched from Clousre to a dictionary and pass that dict to a function and do anything you want to do or use escaping blocks
func getAllMessagesSent(snapshot: [String:AnyObject]) {
//data is here
}
这篇关于如何将数据传递到从Firebase检索信息的闭包之外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!