我意识到这有点乱,但我正在通过从教程和参考资料中拼凑出各种东西来了解事情是如何工作的。 我的问题是当我从firebase中删除一个节点时,tableview不会更新。它已从firebase中删除,但单元格仍保留在tableview中。虽然下面没有显示,但我尝试在我认为应该去的地方添加mytableview.reload代码块,但我没有成功。任何意见都表示赞赏。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventsList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! ViewControllerTableViewCell
cell.locationLabel.text = eventsList[indexPath.row].location
cell.eventTimeLabel.text = eventsList[indexPath.row].dateTime
cell.eventTypeLabel.text = eventsList[indexPath.row].agencyEventSubtypeCode
cell.agencyIdLabel.text = eventsList[indexPath.row].agencyId
if eventsList[indexPath.row].alarmLevel == "1" {
cell.locationLabel.textColor = UIColor.red
cell.eventTimeLabel.textColor = UIColor.red
cell.eventTypeLabel.textColor = UIColor.red
cell.agencyIdLabel.textColor = UIColor.red
}
return cell
}
ref = Database.database().reference()
fetchData()
}
func fetchData(){
refHandle = ref?.child("caddata").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: Any] {
let event = Events()
event.setValuesForKeys(dictionary)
if event.originatingAction == "CadEventNew" {
self.eventsList.append(event)
DispatchQueue.main.async {
self.myTableView.reloadData()
}
} else if event.originatingAction == "CadCloseEvent" {
self.cadPacketType = event.originatingAction
self.cadEventNumber = event.agencyEventId
self.queryCloseUIDFromDB()
}
}
})
}
func queryCloseUIDFromDB(){
if cadPacketType == "CadCloseEvent" {
let dataRef = ref?.child("caddata")
let queryRef = dataRef?.queryOrdered(byChild: "agencyEventId")
.queryEqual(toValue: cadEventNumber)
queryRef?.observeSingleEvent(of: .value, with: { (snapshot) in
for snap in snapshot.children {
let dataSnap = snap as! DataSnapshot
self.closeUID = dataSnap.key //the uid of each event
if self.closeUID != nil {
self.deleteFromDB()
DispatchQueue.main.async {
self.myTableView.reloadData()
}
}
}
})
}
}
func deleteFromDB () {
if closeUID != nil {
print (cadEventNumber!)
print (closeUID!)
ref?.child("caddata").child(closeUID!).removeValue(completionBlock: { (error, ref) in
if error != nil {
self.fetchData()
print("Error: \(String(describing: error))")
return
}
})
}
print ("\(String(describing: closeUID)) has been removed")
}
答案 0 :(得分:0)
删除后需要再次获取数据
将此deleteFromDB
方法替换为此方法,必须执行fetchData if error == nil
func deleteFromDB () {
if closeUID != nil {
print (cadEventNumber!)
print (closeUID!)
ref?.child("caddata").child(closeUID!).removeValue(completionBlock: { (error, ref) in
if error != nil {
print("Error: \(String(describing: error))")
return
}
//clean the array
self.eventsList.removeAll()
self.fetchData()
})
}
print ("\(String(describing: closeUID)) has been removed")
}