&Swiftラーニング-Firestoreの更新を聴く(英語)


Listening for Updates on Firestore

  • In order to retrieve data from Firestore, you would initially have to repeatedly call the below function (closure)
  • db.collection().getDocuments { }
    → But instead, there is a way to get realtime updates with Firestore.

    ex. Code from Firebase Documents
    db.collection("cities").document("SF")
        .addSnapshotListener { documentSnapshot, error in
          guard let document = documentSnapshot else {
            print("Error fetching document: \(error!)")
            return
          }
          guard let data = document.data() else {
            print("Document data was empty.")
            return
          }
          print("Current data: \(data)")
        }
    → The above code allows us to addSnapshotListener so that whenever new documents are added to a particular collection, we get our code to be triggered again.
    Hence, if we want to get our data just once, we would use the aforementioned getDocument method, but if we need to constantly retrieve data from our Firestore, we could add a snap shot listener.
    Whenever a new item is added, the closure part is triggered. Therefore, in a chat application, we want the closure part to be triggered whenever a new message is sent. When we send our message, we add a new document into Firestore. This triggeres the addSnapshotListener, hence triggering the closure part.
    func loadMessages(){
     
            db.collection(K.FStore.collectionName).addSnapshotListener { (querySnapshot, err) in
                
                self.messages = []
                
                if let err = err{
                    print("There was an issue retrieving data from Firestore \(err)")
                }
                else{
                    
                    if let snapshotDocuments = querySnapshot?.documents{
                        
                        for doc in snapshotDocuments{
                            let data = doc.data()
                            if let messageSender = data[K.FStore.senderField] as? String, let messageBody = data[K.FStore.bodyField] as? String{
                                
                                let newMessage = Message(sender: messageSender, body: messageBody)
                                self.messages.append(newMessage)
                                 
                                DispatchQueue.main.async {      // We are in a closure, meaning the method 수행 is happening in the
                                                                // background. But when we need to update the tableView, we have to
                                                                // do this in the main thread
                                    
                              
                                    self.tableView.reloadData()
                                }
                            }
                        }
                        
    
                    }
                }
            }
        }