You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift删除TableViewCell时调用Database.database()报‘找不到Database’错误求助

问题分析与解决方案

错误根源

你遇到的cannot find Database in scope错误有两个核心原因:

  1. Database是Firebase实时数据库的专属类,你的Podfile中未添加Firebase/Database依赖,因此编译器找不到该类。
  2. 从你的代码逻辑来看,全程使用的是Firebase云Firestore(通过db.collection("tweet")操作),完全不需要调用实时数据库的Database类,属于API用错了场景。

以下是针对你现有Firestore架构的完整修复方案:


步骤1:修正 tweet 模型,存储文档ID

Firestore删除文档必须依赖唯一的documentID,因此需要给你的tweet结构体添加该属性:

struct tweet {
    var name: String
    var content: String
    var timeStamp: Date
    var documentID: String? // 新增存储文档ID的属性
    
    // 初始化方法适配
    init(name: String, content: String, timeStamp: Date, documentID: String? = nil) {
        self.name = name
        self.content = content
        self.timeStamp = timeStamp
        self.documentID = documentID
    }
    
    // 从字典初始化时同步传入文档ID
    init?(dictionary: [String: Any], documentID: String? = nil) {
        guard let name = dictionary["name"] as? String,
              let content = dictionary["content"] as? String,
              let timeStamp = dictionary["timeStamp"] as? Date else {
            return nil
        }
        self.name = name
        self.content = content
        self.timeStamp = timeStamp
        self.documentID = documentID
    }
    
    // 保持原有的字典转换方法
    var dictionary: [String: Any] {
        return [
            "name": name,
            "content": content,
            "timeStamp": timeStamp
        ]
    }
}

步骤2:修改数据加载方法,存入文档ID

更新loadData和checkForUpdates方法,将Firestore返回的文档ID同步存入tweet对象:

func loadData() {
    db.collection("tweet").getDocuments() {
        querySnapshot, error in
        if let error = error {
            print("\(error.localizedDescription)")
        }else{
            // 加载时同步获取文档ID
            self.tweetArray = querySnapshot!.documents.compactMap { doc in
                tweet(dictionary: doc.data(), documentID: doc.documentID)
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
}

func checkForUpdates() {
    db.collection("tweet").whereField("timeStamp", isGreaterThan: Date())
        .addSnapshotListener {
            querySnapshot, error in
            guard let snapshots = querySnapshot else {return}
            
            snapshots.documentChanges.forEach {
                diff in
                
                if diff.type == .added {
                    // 新增数据时同步存入文档ID
                    if let newTweet = tweet(dictionary: diff.document.data(), documentID: diff.document.documentID) {
                        self.tweetArray.append(newTweet)
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    }
                }
            }
        }
}

步骤3:实现正确的Firestore删除逻辑

替换你原有的commit editingStyle方法,完成本地数据与Firestore数据的同步删除:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    guard editingStyle == .delete else { return }
    
    let targetTweet = tweetArray[indexPath.row]
    guard let docID = targetTweet.documentID else {
        print("无法获取文档ID,删除失败")
        return
    }
    
    // 1. 删除Firestore中的对应文档
    db.collection("tweet").document(docID).delete { error in
        if let error = error {
            print("删除文档失败:\(error.localizedDescription)")
        } else {
            // 2. 删除本地数组数据并刷新表格
            DispatchQueue.main.async {
                self.tweetArray.remove(at: indexPath.row)
                self.tableView.deleteRows(at: [indexPath], with: .automatic)
            }
            print("文档删除成功")
        }
    }
}

额外说明(如果你确实需要用实时数据库)

如果你的业务场景需要切换到Firebase实时数据库,需要:

  1. 在Podfile中添加依赖:
pod 'Firebase/Database'
  1. 执行pod install后,在代码中导入FirebaseDatabase:
import FirebaseDatabase

此时Database.database().child("tweet")即可正常使用,但这与你现有代码的Firestore架构冲突,不建议混用。

内容的提问来源于stack exchange,提问作者user21069271

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 19:50:17