我的tableview当前更新了我的表,并在将它们添加到我的firebase数据库时实时添加新项目。问题是我无法实时删除。我将来自firebase的数据存储在本地数组中,然后将该数组加载到tableview中。
我试着压缩我的代码。我还尝试将我的removeDeletedItems()函数中的Firebase代码放在我的populateArrays()函数中,并将它放在.childAdded监听器之后,但是没有运气实时删除数据。
override func viewDidLoad() {
super.viewDidLoad()
populateArrays()
}
func removeDeletedItems() {
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("Users").observe(FIRDataEventType.childRemoved, with: { (FIRDataSnapshot) in
guard let emailToFind = FIRDataSnapshot.value as? String else { return }
for (index, email) in self.usernames.enumerated() {
if email == emailToFind {
let indexPath = IndexPath(row: index, section: 0)
self.usernames.remove(at: index)
self.tableView.deleteRows(at: [indexPath], with: .fade)
self.tableView.reloadData()
}
}
})
}
func populateArrays(){
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("Users").observe(FIRDataEventType.childAdded, with: { (FIRDataSnapshot) in
if let data = FIRDataSnapshot.value as? NSDictionary {
if let name = data[Constants.NAME] as? String {
self.usernames.append(name)
self.removeDeletedItems()
self.tableView.reloadData()
}
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = usernames[indexPath.row]
return cell
}
答案 0 :(得分:1)
观察到的值总是不是字典吗?你也不应该检查名称而不是电子邮件吗?
不需要循环来查找名称。有一个便利功能。
databaseRef.child("Users").observe(FIRDataEventType.childRemoved, with: { snapshot in
guard let data = snapshot.value as? [String:Any],
let nameToFind = data[Constants.NAME] as? String else { return }
if let index = self.usernames.index(of: nameToFind) {
let indexPath = IndexPath(row: index, section: 0)
self.usernames.remove(at: index)
self.tableView.deleteRows(at: [indexPath], with: .fade)
// don't reload the table view after calling `deleteRows`
}
}
})