&Swiftラーニング-Firestoreの更新を聴く(英語)
Listening for Updates on Firestore
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()
}
}
}
}
}
}
}
Reference
この問題について(&Swiftラーニング-Firestoreの更新を聴く(英語)), 我々は、より多くの情報をここで見つけました https://velog.io/@kevinkim2586/iOS-Swift-공부-Listening-for-Updates-on-Firestore-영テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol