Swift 无法在堆栈中找到工作答案:如何知道Firebase何时检索数据
请解释我需要从Firebase检索数据的位置(方法或可能存在的观察竞争方法)。什么是最佳实践Swift 无法在堆栈中找到工作答案:如何知道Firebase何时检索数据,swift,firebase,firebase-realtime-database,Swift,Firebase,Firebase Realtime Database,请解释我需要从Firebase检索数据的位置(方法或可能存在的观察竞争方法)。什么是最佳实践 var ref:FIRDatabaseReference! ref = FIRDatabase.database().reference() //filling ShopList by favorite ref.child("goods").observeSingleEvent(of:.value, with: {(snapshot) in if le
var ref:FIRDatabaseReference!
ref = FIRDatabase.database().reference()
//filling ShopList by favorite
ref.child("goods").observeSingleEvent(of:.value, with: {(snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
print("my app: 1. Start ObserveSingle")
for snap in snapshots {
let g = Good()
g.barcode = String(describing: snap.childSnapshot(forPath: "barcode").value!)
g.name = snap.childSnapshot(forPath: "name").value! as! String
g.price = snap.childSnapshot(forPath: "minprice").value! as! Double
g.favorite = snap.childSnapshot(forPath: "favorite").value! as! Bool
if g.favorite {//избранные товары
DataService.dataService.dbShopList.append(g)
}
}
print("my app: 2. Observe finished \(DataService.dataService.dbShopList.count)")
}
})
print("my app: 3. observe finished \(DataService.dataService.dbShopList.count)")
如何理解何时何地完成步骤2
下面调试
my app: 3. observe finished 0
my app: 1. Start ObserveSingle
my app: 2. Observe finished 3
Firebase数据仅在事件发生后的关闭内有效。所以当你打电话的时候
ref.child("goods").observeSingleEvent(of:.value, with: {
//this is the closure where the data is returned and valid
})
这是格查
print("my app: 3.
将在之前被呼叫
print("my app: 2.
因为代码执行速度比互联网快
Firebase返回数据时出现延迟,这将导致在关闭之外的print语句之后触发关闭
在闭包内使用Firebase数据,因为这是它唯一有效的时间。在数据准备就绪之前尝试访问该数据将导致nil数据,因为在调用闭包之前不会填充变量
根据返回的Firebase数据设置事件序列需要时间
下面是一些伪代码:
myDataSource = []
Query Firebase for data {
populate the data source with Firebase data
reload the tableView
}
don't access the data source here as it won't be ready
我们可以使用您问题中的一段代码将其付诸实践
var ref:FIRDatabaseReference!
ref = FIRDatabase.database().reference()
ref.child("goods").observeSingleEvent(of:.value, with: {(snapshot) in
print("data from the snapshot is ready to be used")
for child in snapshot.children {
var g = Good()
let snap = child as! FIRDataSnapshot
let dict = snap.value! as! [String:String]
g.barcode = dict["barcode"]!
DataService.dataService.dbShopList.append(g)
}
print("All the firebase data was read in, show it in the tableView")
self.tableView.reloadData()
})
print("This will execute before the closure completes so")
print(" don't do anything with the Firebase data here")
你想问什么?当事情发生时,你的指纹会告诉你。谢谢你的理论,你能给出一个实践例子吗?@leoninfi我不确定你是否能给出一个例子,因为你的代码很好-问题在于理解数据流。Firebase本质上是异步的,因此在Firebase返回快照数据之前,您无法处理该数据,而该数据仅在observe闭包内有效。我添加了一些示例代码(未经测试,因为我在iPad上),可以帮助您完成流程。