Firestore集合已存在时如何捕获错误? [英] How to catch error when Firestore collection already exists?

查看:39
本文介绍了Firestore集合已存在时如何捕获错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,当Firebase Firestore中已经存在一个集合时,我的应用程序崩溃了.我想在发生此错误时捕获该错误,但是由于 addSnapshotListener()方法不会引发任何错误,因此我的当前实现无法捕获任何错误.

Right now my app is crashing when a collection already exists in Firebase Firestore. I want to catch this error when it happens, but my current implementation doesn't catch anything as the addSnapshotListener() method does not throw any error.

当前代码

let db = Firestore.firestore()
        
        do {
            try db.collection(chatName).addSnapshotListener { (Query, Error) in
                if Error != nil || Query?.documents != nil {
                    let alert = UIAlertController(title: "Chat Name Already Exists", message: "This chat name already exists, try again with a different name", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: { (UIAlertAction) in
                        alert.dismiss(animated: true, completion: nil)}))
                    AllChatsViewController().present(alert, animated: true)
                    completion()
                }
                else {
                    self.addChatToProfile(withName: chatName) {
                        completion()
                    }
                }
            }
        }
        catch {
            let alert = UIAlertController(title: "Chat Name Already Exists", message: "This chat name already exists, try again with a different name", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: { (UIAlertAction) in
                alert.dismiss(animated: true, completion: nil)}))
            AllChatsViewController().present(alert, animated: true)
            completion()
        }

应用崩溃后出错

线程1:无效的集合引用.集合引用的段数必须为奇数,但必须为0"

Thread 1: "Invalid collection reference. Collection references must have an odd number of segments, but has 0"

如何捕获此错误,以便显示带有该错误的UIAlertController?

How can I catch this error so I can display an UIAlertController with the error?

推荐答案

我会使用其他方法.

要测试集合是否存在,请按名称读取该集合,并通过snapshot.count确定是否有任何文档等于0

To test if a collection exists, read that collection by name and determine if there are any documents via snapshot.count equals 0

这里的陷阱是,一个集合可能包含大量数据,没有理由读取所有数据或附加一个侦听器,因此我们需要在该集合中使用一个已知字段来限制结果.

The gotcha here is that a collection could have a large amount of data and there's no reason to read all of that in or attach a listener so we need to use a known field within that collection to limit the results.

我建议使用一个带有闭包的函数,如果该集合存在,则返回true,否则返回false,然后根据该结果采取行动.

I would suggest a function with a closure that returns true if the collection exists, false if not and then take action based on that result.

您将需要要测试的集合的名称,然后需要该集合中的已知字段的名称来查询以限制结果.

You'll need the name of the collection you want to test and then the name of a known field within that collection to query for to limit the results.

字段名称很重要,因为如果集合中有1M个文档,则您不想全部读取它们-您只想读取一个,而.orderBy有一个限制就可以做到这一点.

The field name is important in that if the collection has 1M documents, you don't want to read them all in - you just want to read one and .orderBy with a limit will do that.

这是一个调用函数

func checkCollection() {
    self.doesCollectionExist(collectionName: "test_collection", fieldName: "msg", completion: { isEmpty in
        if isEmpty == true {
            print("collection does not exist")
        } else {
            print("collection found!")
        }
    })
}

然后是通过读取一个文档来检查集合是否存在的函数,如果不存在则返回false,否则返回true.

and then the function that checks to see if the collection exists by reading one document and returns false if not, true if it does.

func doesCollectionExist(collectionName: String, fieldName: String, completion: @escaping ( (Bool) -> Void ) ) {
    let ref = self.db.collection(collectionName)
    let query = ref.order(by: fieldName).limit(toLast: 1)
    query.getDocuments(completion: { snapshot, error in
        if let err = error {
            print(err.localizedDescription)
            return
        }
        
        if snapshot!.count == 0 {
            completion(true)
        } else {
            completion(false)
        }
    })
}

这篇关于Firestore集合已存在时如何捕获错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆