【问题标题】:delete Table View Cells from Firebase从 Firebase 中删除表格视图单元格
【发布时间】:2017-07-13 00:47:33
【问题描述】:

我有一个表格查看完整的附加消息,其中包含登录用户和应用程序的其他用户。当我滑动一个单元格时,我希望能够从 Firebase 中删除它,也可以从 tableView 中自动删除它。我设法从 Firebase 中删除了单元格,但没有从 tableView 中删除。这是消息最初加载到 tableView 中的方式:

  func loadData()
    {
        guard let uid = FIRAuth.auth()?.currentUser?.uid else {
            return
        }
   FIRDatabase.database().reference().child("messages").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

            if let postsDictionary = snapshot .value as? [String: AnyObject] {

                for post in postsDictionary {
                    let messages = post.value as! [String: AnyObject]
                    for (id, value) in messages {
                        let info = value as! [String: AnyObject]


                        let convoId = info["convoId"]
                        let toId = info["ReceiverId"] as! String!
                        let fromId = info["senderId"] as! String!


                        if (toId == self.loggedInUserUid  || fromId == self.loggedInUserUid) {

        let refs = FIRDatabase.database().reference().child("user-messages").child(convoId as! String).child(uid)
        refs.observe(.childAdded, with: { (snapshot) in


            self.messageId = snapshot.key



        let ref = FIRDatabase.database().reference().child("messages").child(convoId as! String).child(self.messageId!)

                            ref.observeSingleEvent(of: .value, with: { (snapshot) in


            if let dictionary = snapshot.value as? [String: AnyObject] {
                let message = Message(dictionary: dictionary)


                if let receiver = message.convoId {
                    self.messagesDictionary[receiver] = message

                    self.messages = Array(self.messagesDictionary.values)
                    print(self.messages)
                    self.messages.sort(by: { (message1, message2) -> Bool in


                        return (message1.timestamp?.int32Value)! > (message2.timestamp?.int32Value)!

                    })
                }

                //this will crash because of background thread, so lets call this on dispatch_async main thread
                DispatchQueue.main.async(execute: {
                    self.MessageTableView.reloadData()
                })
            }

        }, withCancel: nil) })}
                    }

                }}})

    }

这是我在 Firebase 中执行删除功能并尝试在 tableView 中执行删除功能的方式:

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

        if editingStyle == .delete {

        guard let uid = FIRAuth.auth()?.currentUser?.uid else {
            return
        }

        let message = messages[(indexPath.row)]


       self.deletemessage = message.convoId


        FIRDatabase.database().reference().child("messages").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

            if let postsDictionary = snapshot .value as? [String: AnyObject] {

                for post in postsDictionary {
                    let messages = post.value as! [String: AnyObject]
                    for (id, value) in messages {
                        let info = value as! [String: AnyObject]


                        let convoId = info["convoId"]

        let ref = FIRDatabase.database().reference().child("user-messages").child(self.deletemessage!).child(uid)
        ref.observe(.childAdded, with: { (snapshot) in

            self.messageId = snapshot.key

            FIRDatabase.database().reference().child("user-messages").child(self.deletemessage!).child(uid).child( self.messageId!).removeValue(completionBlock: { (error, ref) in
                if error != nil {
                    print("error \(error)")
                }else{



                }})})}}}})

            self.messages.remove(at: indexPath.row)
            self.MessageTableView.deleteRows(at: [indexPath], with: .automatic)

        }
    }

它从 tableView 中删除但崩溃并在self.messages.remove(at: indexPath.row) 致命错误上给我一个错误:索引超出范围。

【问题讨论】:

  • 您想从已验证的用户中删除已登录的用户,还是只删除数据库中的部分数据,如子项?

标签: ios swift firebase firebase-realtime-database firebase-authentication


【解决方案1】:
 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {

            let state = id[indexPath.row] //it store the child key to be removed. here id array is not displayed but used as backend process

            print(state) // (Not required)

            names.remove(at: indexPath.row) //Remove the selected name from array used in TableView that is displayed in cell

            tableView.deleteRows(at: [indexPath], with: .fade) // TableView Animation 

            Database.database().reference().child("artists").child(id[indexPath.row]).removeValue() // remove the child referred using id from database

            id.remove(at: indexPath.row) // removing selected if from id array locally 

        }
    }

请在您的情况下尝试以下代码并让我知道问题仍然存在

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

if editingStyle == .delete {

guard let uid = FIRAuth.auth()?.currentUser?.uid else {
    return
}
let message = messages[(indexPath.row)]

self.deletemessage = message.convoId

FIRDatabase.database().reference().child("messages").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in
    if let postsDictionary = snapshot .value as? [String: AnyObject] {
        for post in postsDictionary {
            let messages = post.value as! [String: AnyObject]
            for (id, value) in messages {
                let info = value as! [String: AnyObject]
                let convoId = info["convoId"]
                let ref = FIRDatabase.database().reference().child("user-messages").child(self.deletemessage!).child(uid)
                ref.observe(.childAdded, with: { (snapshot) in

                    self.messageId = snapshot.key

                    FIRDatabase.database().reference().child("user-messages").child(self.deletemessage!).child(uid).child( self.messageId!).removeValue(completionBlock: { (error, ref) in
                        if error != nil {
                            print("error \(error)")
                        }
                    })
                })
            }
        }}})
    self.messages.remove(at: indexPath.row)
    self.MessageTableView.deleteRows(at: [indexPath], with: .automatic)
}
}

尝试发生这种情况,因为您正在删除正确的值,但在处理程序下,这甚至在我的项目中导致了错误。消息中的数据是从数据库中加载的,因此如果未从数据库中删除值,即使您从数组中删除,它也会再次更新。所以请试试这个代码

【讨论】:

  • 我觉得我做了同样的事情。它会删除,但随后我收到错误致命错误:索引超出范围。
  • 我在我的代码中尝试了您的代码样式,这种情况是否与从 firebase 中删除值相同,但是从 tableview 中删除值时会崩溃,并且当您重新加载应用程序时,您尝试删除的名称是删除 d?
  • 它可以工作并且不会崩溃。但是,当我向用户输入新消息时,这些消息会自动删除,而无需我滑动删除
  • 我输入时消息不会被删除的唯一一次是我重新启动应用程序时
  • 之前的问题解决了吗?并且当您使用滑动删除一条消息时,然后在同一次启动中键入一条新消息时,它会自动删除而不从数据库中滑动?
猜你喜欢
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多