首页 > 解决方案 > 根据添加或删除的 Firestore 文档的变化重新加载 tableView

问题描述

每当将新文档添加到 Firestore 或删除时如何重新加载表格视图这是我的问题:

我正在调用此函数feachOrder()viewDidLoad()因此在添加或删除文档后,在我关闭应用程序并再次重新打开它或再次运行它之前,它不会监听 Firestore 中的更改,我想要的是一旦添加了新文档, tableView 重新加载数据并立即获取值

func fetchOrder(){
        
        let fireStore = Firestore.firestore()
        let doc = fireStore.collection("طلب").document(Auth.auth().currentUser!.uid)
        self.doc = doc.documentID
        
        doc.getDocument { (snapshot, error) in
            if error != nil {
                debugPrint("error fitching\(String(describing: error))")
            }else{
                guard let snap = snapshot?.data() else {return}
                
                let name = snap["name"] as? String ?? ""
                let phone = snap["phone"] as? String ?? ""
                let orderText = snap["order"] as? String ?? ""
                let time = snap["time"] as? String ?? ""
                let price = snap["amount"] as? String ?? ""
                guard let orderLocation = snap["orderLocation"] as? GeoPoint else{return}
                guard let userLocation = snap["userLocation"] as? GeoPoint else {return}
                
                DispatchQueue.main.async {
                    UIView.animate(withDuration: 2 , delay: 2, options: .allowAnimatedContent, animations: {
                                   self.emptyView.isHidden = true
                               }, completion: nil)
                               
                    let myOrder = myOrderData(name: name, phone: phone, amount: price, time: time, orderDetails: orderText, orderLocation: orderLocation, myLocation: userLocation)
                                   self.orders.append(myOrder)
                    self.ordersTV.reloadData()
                    
                }
                               
                
            }
           
            
        }
        
        
    }

标签: iosswiftgoogle-cloud-firestore

解决方案


你想要的是一个快照监听器。本文档应该对您有所帮助https://firebase.google.com/docs/firestore/query-data/listen#swift_1

在您的示例中,您只需通过let collection = fireStore.collection("طلب"). 然后您可以通过执行以下操作来创建快照侦听器:

collection.addSnapshotListener { (snapshot, error)
  // TODO Handle error

  // Handle each change based on what kind of update it is
  snapshot?.documentChanges.forEach({ (change) in
     switch change.type {
       case .added:
         // A document has been added to the collection
         self.tableview.reloadData()
       case .modified:
         // A document in the collection has been modified
       case .removed:
         // A document has been removed from the collection
     }
  }
}

您只需调用此函数一次,其余的由 Firebase 处理。

如果需要,您可以从 ViewDidLoad 或其他文件中调用它。如果你从另一个文件中调用它,与你的视图控制器交流更新的最佳方式是使用本地通知。


推荐阅读