ios - Firebase + Swift 在 TableView 中删除行

标签 ios firebase firebase-realtime-database

好的,我正在按照本教程 ( https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2 ) 使用 Firebase 删除 tableView 中的行,但它似乎不起作用。我的代码如下:

override func viewDidLoad() {
    super.viewDidLoad()
    configureDatabase() 
}

func configureDatabase() {
    self.ref = FIRDatabase.database().reference()
    if let user = FIRAuth.auth()?.currentUser {
        self.ref.child("mileage").queryOrderedByChild("user").queryEqualToValue(user.uid).observeEventType(.ChildAdded, withBlock: { (snapshot) in
            self.mileageDatabase.insert(snapshot, atIndex: 0)
            self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .Automatic)

        })


    } else {

    }

}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {
        let row = self.mileageDatabase[indexPath.row]
        row.ref.removeValue()
        self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row, inSection: 0)], withRowAnimation: .Automatic)

    }
}

它抛出错误:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (8) must be equal to the number of rows contained in that section before the update (8), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

最佳答案

我认为这里 row.ref.removeValue() 有一个错误。您正在将 Array 与 Firebase 数据混合在一起。如果你只写:

mileageDatabase.remove[indexPath.row] tableview.reloadData()

对我来说就是这样工作的。您必须捕获该行的用户 key 。 我有一个像你的数组 (mileageDatabase = teste),但我的变量存储在 sublcass (ChkList) 内的结构中。我就是这样做的。

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

if editingStyle == .delete {

        let user: ChkList = teste[indexPath.row]
        let uk = user.key
        print("Userkey: \(uk)")
        ref.child(uk!).removeValue()
}
}

这样您就可以从 Firebase 和表格 View 中删除数据。您可以在以下位置查看我的问题:Firebase: delete item from row (Swift 3)

关于ios - Firebase + Swift 在 TableView 中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674543/

相关文章:

ios - 解析 - imageView 作为 PFFile 不会加载

android - 获取嵌套数据库 firebase android 中的最后一项

javascript - Firebase 有时连接,有时不连接(React Native)

java - 如何使用未知节点将 Firebase 数据库中的值显示到 Firebase 回收 View ?

javascript - Vue.js + Firebase - 如何显示深度嵌套的数据库

ios - 切换以启用/禁用本地通知(swift 4)

ios - 使用的设备可用空间和沙箱空间

ios - UISearchController 的 init(searchResultsController : UIViewController?) 崩溃

android - Firebase 远程配置和 Microsoft Codepush 之间的区别

javascript - 从 Firebase 获取随机项目