Crashes with Firestore

2 Solutions Collect From Internet About “Crashes with Firestore”

I’ve found this can be solved with a nifty little guard statement:

guard (documentSnap?.exists ?? false), error == nil else { return }

Here’s a working example of this check:

func getUserData(uid: String, completion: @escaping(([String: Any]?, Error?)) -> ()) {

        let document = defaultStore.collection("user-data").document(uid)

        document.getDocument { (documentSnap, error) in

            guard (documentSnap?.exists ?? false), error == nil else {
                completion((nil, error))
                return
            }

            completion((documentSnap?.data(), error))
}}

I don’t know why you have to call .exists(), and the document isn’t just nil, but this is either part of the learning curve, or an artifact of a Beta SDK

This is how I handle if there is a snapshot or not.

func fetchCity(city: String, completion: @escaping (_ isSuccess: Bool, _ document: DocumentSnapshot?)->()){
            REF_CITIES.document(city).getDocument { (document, err) in
                if (document?.exists)! {
                    completion(true, document)
                }else {
                    print(err?.localizedDescription)
                    completion(false, nil)
                }
            }
        }

You can use .exists only for DocumentSnapshot. You can’t use it for QuerySnapshot because QuerySnapshot actually is a multiple DocumentSnapshot.