我正在尝试从Firebase Firestore文档中下载信息,然后将其实时附加到数组中。每当我添加文档,删除或编辑文档时,我都希望该应用程序更新并同步数组以匹配数据。我能够使用以下代码检索数据:
database.collection("_Products").getDocuments(completion: { (snapshot, error) in
if error != nil {
print(error as Any)
}else{
for document in (snapshot?.documents)! {
let Name = document.data()["Item Name"] as! String
let Price = document.data()["Item Price"] as! String
let Number = document.data()["Item Number"] as! String
let Brand = document.data()["Item Brand"] as! String
let Quantity = document.data()["Quantity"] as! String
let Category = document.data()["Item Category"] as! String
DispatchQueue.main.async {
if instoreCheckOutArray.contains(where: {$0.Number == Number && $0.Brand == Brand}){
return
}else{
instoreCheckOutArray.append(checkOutArrayInfo(Brand: Brand, Name: Name, Number: Number, Price: Price, Quantity: Quantity, Category: Category))
self.searchForCoupon()
}
}
}
}
})
然后我使用以下代码每秒运行一次该函数以从数据库中获取数据:
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCart), userInfo: nil, repeats: true)
运行先前的代码可以完美地获取新数据,但是我无法让应用程序更新现有数组以匹配数据库,并且当我从数据库中删除文档时,它会保留在数组中。
谢谢你。
答案 0 :(得分:0)
1。声明scrollingTimer变量
var scrollingTimer = Timer()
2。使用您的函数初始化scrollingTimer
scrollingTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCart), userInfo: nil, repeats: true)
3。启动scrollingTimer(在任意位置触发)
scrollingTimer.fire()
要停止滚动计时器,请使用以下行(请在任意位置停止)
scrollingTimer.invalidate()
如果有的话,请参考link(DevelopersDocument)