gpt4 book ai didi

ios - 捕获Firebase实时observeSingleEvent数据在首次调用时失败

转载 作者:行者123 更新时间:2023-12-01 21:58:03 26 4
gpt4 key购买 nike

我与Firebase实时数据库有正常的连接。通过点击IBAction按钮触发watchSingleEvent。首次调用以获取数据失败。第二次按下按钮将获取数据。第一次调用时如何获取数据?我试过多次调用observeSingleEvent,以编程方式点击按钮并添加等待以使observeSingleEvent完成。甚至在绝望时添加了完成块。我做错了什么提示将不胜感激。

-编辑-

修复了@rob建议的以下代码。 Rob回答的唯一补充是,在完成块的定义中需要@escaping。现在工作精美。

var prodNo: String = "XXX000000"
var productDataLocal: [String: String] = ["ProdNo": "", "Location": ""]

@IBAction func findTapped(_ sender: Any) {
fetchFirebaseData { () -> () in
if productDataLocal["ProdNo"] == prodNo { // check that the data matches the product
// launch a segue (that is detached from button)
self.performSegue(withIdentifier: "moveToDetail", sender: nil)
}
else {
showError("Product \(prodNo) can't be found.")
}
}
} // findTapped

func fetchFirebaseData(completion: @escaping () -> ()) { // --- EDIT ---@escaping addedd
// check if this product can be found in Firebase!
self.ref.child("Id").child("\(prodNo)").observeSingleEvent(of: .value, with:
{ (snapshot) in
// try if this product can be found in Firebase
let tempData = snapshot.value as? Dictionary<String, Any>
if let actualData = tempData {
self.copyData(actualData)
}
completion() // --- EDIT --- completion moved here
}) { (error) in
print(error.localizedDescription)
completion() // --- EDIT ---and completion moved here
}
// --- EDIT -- completion() removed from here
} // fetchFirebaseData

func copyData(_ actualData: Dictionary<String, Any>) {
dump(actualData) // for debugging what "actualData" actually contains
// this is always OK when execution gets here
self.productDataLocal["ProdNo"] = actualData["ProdNo"] as? String
self.productDataLocal["Location"] = actualData["Location"] as? String
}

执行时,“实际”数据的转储起作用并产生正确的数据。问题是我无法找到任何方法来执行此代码,而是第二次按下按钮。 (是的,在JSON结构中重复了“ProdNo”,以便我可以检查它是否与请求的产品编号匹配。)---编辑---上面的代码现在可以解决问题
▿ 2 key/value pairs
▿ (2 elements)
- key: "ProdNo"
- value: XXX000000 #0
- super: NSMutableString
- super: NSString
- super: NSObject
▿ (2 elements)
- key: "Location"
- value: "Warehouse 1" #1
- super: NSMutableString
- super: NSString
- super: NSObject

最佳答案

您正在同步调用完成块。在observeSingleEvent完成之前,您不应调用它。如果将完成块移至observeSingleEvent处理程序,则应获得所需的结果:

func fetchFirebaseData(completion: @escaping () -> ()) { // --- EDIT --- added "@escaping
// check if this product can be found in Firebase!
self.ref.child("Id").child("\(prodNo)").observeSingleEvent(of: .value, with: { (snapshot) in
// try if this product can be found in Firebase
let tempData = snapshot.value as? Dictionary<String, Any>
if let actualData = tempData {
self.copyData(actualData)
}
completion()
}) { (error) in
print(error.localizedDescription)
completion()
}
} // fetchFirebaseData

关于ios - 捕获Firebase实时observeSingleEvent数据在首次调用时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61019386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com