我試圖將我從我的firebase數據庫檢索到的數據傳遞到我的單身人員的字段中。數據通過閉包接收,並在該閉包中傳遞一些數據到我的單身人士的屬性。如果我在封閉內部打印數據結構(在分配了所有東西之後),我得到了我期望的輸出,但是如果我在所有數據傳入之後將其打印在初始化程序的末尾,則它是空的。如何將數據傳遞給從Firebase中檢索信息的閉包?
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獲取數據時,調用是異步的,因此外部打印會在之前調用。 –
請按照此鏈接(https://stackoverflow.com/questions/38364288/getting-data-out-of-a-closure-that-retrieves-data-from-firebase?rq=1) –