[英]Swift firebase when retrieving data from the database, how to delay the next code until the retrieval is done?
我正在使用Firebase實時數據庫,在特定時間執行代碼時遇到麻煩。 當我詢問數據庫中是否有特定值時,它會執行代碼以檢索數據,然后自動繼續到下一行,而不等待數據的檢索。 我正在使用以下代碼來檢索數據:
self.ref.child("Period \(periodListValue)").child("Students").child("\(studentName)").child("Novel Author").observeSingleEvent(of: .value) { (snapshot) in
self.CurrentAuthorTextField.text = (snapshot.value as! String)
}
與該代碼不相關的代碼行下面的代碼行,在上面的代碼執行后立即執行。 意思是我不能在上面顯示的代碼正下方使用任何代碼的數據庫信息。
我正盡力解釋這一點。
有什么幫助嗎?
好吧,您必須使用完成處理程序進行以下操作:
func ifStudentPresent(studentName: String, completionHandler: @escaping ((_ exist : Bool) -> Void))
{
self.ref.child("Period \(periodListValue)").child("Students").child("\ .
(studentName)").child(studentName).observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists(){
completionHandler(true)
}else{
print("Student Don't exist")
completionHandler(false)
}
})
}
您可能要解決此問題的原因與無效的數據庫安全規則有關。 這些可以輕松阻止您檢索所需的數據並同步實時數據庫。
假設您正在嘗試同步ref
數據庫引用。 您需要設置正確的規則以允許從該數據庫引用中進行讀取 -類似於".read" = true"
。
[警告]請謹慎使用這些數據庫安全規則。 錯誤的規則可能導致嚴重的不良行為,例如人們非法從數據庫中讀取和/或寫入數據庫。 有關如何設置完美安全規則的精彩視頻是Firebase安全性的關鍵-Google I / O 2016
let dispatch = DispatchGroup.init()
dispatch.enter()
self.ref.child("Period \(periodListValue)").child("Students").child("\(studentName)").child("Novel Author").observeSingleEvent(of: .value) { (snapshot)
in
self.CurrentAuthorTextField.text = (snapshot.value as! String)
dispatch.leave()
}
dispatch.notify(queue: .main) {
//write code here, it will execute after database fetch
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.