Reputation: 81
how to reload the table view whenever a new document is added to the firestore or deleted this is my Q:
I'm calling this func feachOrder()
on viewDidLoad()
so after the document is added or deleted it will not listen to that change in firestore until I close the app and reopen it again or run it again, what I want is that once a new document is added, the tableView reload the data and get the values immediately
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()
}
}
}
}
Upvotes: 0
Views: 222
Reputation: 385
What you want is a snapshot listener. This documentation should be helpful to you https://firebase.google.com/docs/firestore/query-data/listen#swift_1
In your example, you would just access the collection by let collection = fireStore.collection("طلب")
. Then you can create the snapshot listener by doing something like this:
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
}
}
}
You only need to call this function once, and Firebase will take care of the rest.
You can call it from your ViewDidLoad or from another file if you want. If you call it from another file, the best way to communicate updates with your view controller is using local notifications.
Upvotes: 2