【问题标题】:Delete cell from UITableView and Firebase从 UITableView 和 Firebase 中删除单元格
【发布时间】:2018-10-17 03:47:53
【问题描述】:

我尝试删除单元格(向左滑动)并从 Firebase 数据库和存储中删除数据。使用此代码:

struct Records {

let title: String
let source: String
var length: String
let recordUrl: String
let username: String

init(dictionary: [String: Any]) {
    self.title = dictionary["title"] as? String ?? ""
    self.source = dictionary["source"] as? String ?? ""
    self.length = dictionary["length"] as? String ?? ""
    self.recordUrl = dictionary["recordUrl"] as? String ?? ""
    self.username = dictionary["username"] as? String ?? ""
}
}

我有一个变量

var records = [Records]()

试图删除单元格

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
   guard let uid = Auth.auth().currentUser?.uid else { return }
    if (editingStyle == .delete) {
        records.remove(at: indexPath.item)
        tableView.deleteRows(at: [indexPath], with: .fade)
       Database.database().reference().child("users").child(uid).child("records").removeValue()
    }
    }

Firebase JSON enter image description here

我需要删除“记录”中的项目(在我的 TableView 中显示为单元格),但现在使用我的代码我删除了整个“记录”

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您还需要保存记录的 ID。通过这种方式,您可以创建指向该特定记录的路径。之后,只需在路径中再添加一个孩子。

    像这样。

    Database.database().reference().child("users").child(uid).child("records").child(record.id).removeValue()
    

    【讨论】:

    • 嗨,rv7284。谢谢,好主意,但是如何为每条记录创建一个 ID?)
    • 你已经做到了。查看每条记录如何属于唯一键。您必须使用 childByAutoId()。您可以使用“.key”从该部分获取该 ID。
    【解决方案2】:

    有一些新的。可以获取分支“记录”中所有项目的键

    guard let uid = Auth.auth().currentUser?.uid else { return }
    let ref = Database.database().reference().child("users").child(uid).child("records")
    ref.observeSingleEvent(of: .value, with: { (snapshot) in
    
    guard let dictionaries = snapshot.value as? [String: Any] else { return }
    let record = self.records[indexPath.item]
    dictionaries.forEach({ (key, value) in
                    print("Key \(key)")
    

    但仍然无法获取要删除当前项目的 ID(分支“记录”中的记录)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      相关资源
      最近更新 更多