iOS Firestore 'Document path cannot be empty'

Viewed 1477

This is not a question, but a solution to the error:

*** Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Document path cannot be empty.'
terminating with uncaught exception of type NSException

Some people would get a similar issue because in an older version of Firebase, the check statements for document would only check for a nil string rather than an empty. The latests versions of Firebase check for nil and an empty string.

2 Answers

The reason why my app would crash:

I would initiate a sign in/ sign up view if the user is not signed in, if they are signed in then the app initiates a homeview, pretty common stuff. The issue was that I had created an instance of currentUser?.Uid as the document path, which would return empty if the user is not signed in, no user signed in means no UID which means no document path.

My firestore would go Users -> UID -> User.

Conclusion

If you have this issue make sure you are not creating an instance of currentUser?.UID for a document path anywhere in your app unless the user is signed in.

I had same issue and my app would crash.

My code was:

func doesUserExist(completion: @escaping (Bool) -> Void) {
    guard AuthService.shared.Auth.auth().currentUser != nil else { return }
    firestore.collection("users").document(auth.currentUser?.uid ?? "").getDocument { snapshot, error in
        if snapshot != nil && error == nil {
            completion(snapshot!.exists)
        } else { completion(false) }
    }
}

^This would return empty document path. So I changed my code to the following and it solved it:

func currentUserDoc() -> DocumentReference? {
    if AuthService.shared.Auth.auth().currentUser != nil {
        return firestore.collection("users").document(auth.currentUser?.uid ?? "")
    }
    return nil
}

func doesUserExist(completion: @escaping (Bool) -> Void) {
    guard AuthService.shared.Auth.auth().currentUser != nil else { return }
    currentUserDoc()?.getDocument { snapshot, error in
        if snapshot != nil && error == nil {
            completion(snapshot!.exists)
        } else { completion(false) }
    }
}

Hope it helps anyone.

Related