Crashes with Firestore

2019-08-17 23:23发布

When I query a collection for a document that doesn't exist, I'm still returned a non-nil object, which crashes when I try to call documentSnapshot?.data().

The error returned is "Document '<FSTDocumentKey: XXXXXX>' doesn't exist. Check document.exists to make sure the document exists before calling document.data.'"

2条回答
We Are One
2楼-- · 2019-08-18 00:13

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.

查看更多
Evening l夕情丶
3楼-- · 2019-08-18 00:15

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

查看更多
登录 后发表回答