与Firestore崩溃
当我查询一个不存在的文档的集合时,我仍然返回一个非零对象,当我尝试调用documentSnapshot?.data()
时崩溃。
返回的错误是"Document '<FSTDocumentKey: XXXXXX>' doesn't exist. Check document.exists to make sure the document exists before calling document.data.'"
我发现这可以用一个漂亮的小警戒声明来解决:
guard (documentSnap?.exists ?? false), error == nil else { return }
这是这个检查的一个工作示例:
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)) }}
我不知道为什么你必须调用.exists()
,并且文档不是零,但是这是学习曲线的一部分,或者Beta SDK的工件
这是我如何处理,如果有快照或不。
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) } } }
您只能使用.exists仅用于DocumentSnapshot。 您不能将其用于QuerySnapshot,因为QuerySnapshot实际上是多个DocumentSnapshot。