M1L10 : Listening for Changes

Lesson 10 from Module 1 of the CWC+ iOS Database course teaches us how to be notified of changes to our Firestore collections and databases.

This code would notify us of any changes in the collection. Every time the collection changes, the completion handler will run.

let db = Firestore.firestore()
let myCollection = db.collection("collection-name")
let collectionListener = myCollection.addSnapshotListener { querySnapshot, error in
    for doc in querySnapshot!.documentChanges {
        print(doc.document.data())
    }
}

When we’re done with listening to the collection, we should turn off the listener, thus:

collectionListener.remove()

To listen to a single document within the collection, we could use this code:

let db = Firestore.firestore()
let myCollection = db.collection("collection-name")
let myDocument = myCollection.document("document-name")
let documentListener = document.addSnapshotListener { docSnapshot, error in
    print(docSnapshot!.data())
}

And, again, to stop the listener:

documentListener.remove()

The above code is for reference, and should really be used together with error handling because we’re force unwrapping and we should check for nil.