首页 > 解决方案 > Firestore:使用 SnapshotListener 调用异步函数并使用 DispatchGroup 循环导致崩溃

问题描述

我在将 DispatchGroup与 FireStore snapshotListener一起使用时遇到了问题(如这里推荐的那样)

在我的示例中,我有两个功能。第一个由 ViewController 调用,应该返回要在 View 中显示的对象数组。第二个是从 FireStore 为每个数组成员获取子对象的函数。它们都必须异步执行。第二个应该循环调用。

所以我使用 DispatchGroup 等到第二个函数的所有执行完成来调用 UI 更新。这是我的代码(见评论部分):

/// Async function returns all tables with active sessions (if any)
class func getTablesWithActiveSessionsAsync(completion: @escaping ([Table], Error?) -> Void) {

    let tablesCollection = userData
        .collection("Tables")
        .order(by: "name", descending: false)

    tablesCollection.addSnapshotListener { (snapshot, error) in
        var tables = [Table]()

        if let error = error {
            completion (tables, error)
        }

        if let snapshot = snapshot {
            for document in snapshot.documents {
                let data = document.data()
                let firebaseID = document.documentID
                let tableName = data["name"] as! String
                let tableCapacity = data["capacity"] as! Int16

                let table = Table(firebaseID: firebaseID, tableName: tableName, tableCapacity: tableCapacity)
                tables.append(table)
            }
        }

        // Get active sessions for each table.
        // Run completion only when the last one is processed.
        let dispatchGroup = DispatchGroup()

        for table in tables {
            dispatchGroup.enter()
            DBQuery.getActiveTableSessionAsync(forTable: table, completion: { (tableSession, error) in
                if let error = error {
                    completion([], error)
                    return
                }
                table.tableSession = tableSession
                dispatchGroup.leave()
            })
        }
        dispatchGroup.notify(queue: DispatchQueue.main) {
            completion(tables, nil)
        }
    }
}

/// Async function returns table session for table or nil if no active session is opened.
class func getActiveTableSessionAsync (forTable table: Table, completion: @escaping (TableSession?, Error?) -> Void) {

    let tableSessionCollection = userData
        .collection("Tables")
        .document(table.firebaseID!)
        .collection("ActiveSessions")

    tableSessionCollection.addSnapshotListener { (snapshot, error) in
        if let error = error {
            completion(nil, error)
            return
        }
        if let snapshot = snapshot {
            guard snapshot.documents.count != 0 else { completion(nil, error); return }

        // some other code

        }
        completion(nil,nil)
    }
}

由于在第二个函数中使用了 snapshotListener ,所以一切正常,直到快照发生更改。更改数据时,将调用以下闭包:

DBQuery.getActiveTableSessionAsync(forTable: table, completion: { (tableSession, error) in
    if let error = error {
        completion([], error)
        return
    }
    table.tableSession = tableSession
    dispatchGroup.leave()
})

它在 dispatchGroup.leave() 步骤上失败,因为此时 group 是空的。

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

所有 dispatchGroup.enter() 和 dispatchGroup.leave() 都已经在这一步完成了。这个闭包是由监听器单独调用的。

我试图找到如何检查 DispatchGroup 是否为空而不调用 leave() 方法的方法。但没有找到任何原生解决方案。我发现的唯一类似的解决方案是在以下答案中。但它看起来太老套了,不确定是否能正常工作。

有什么方法可以检查 DispatchGroup 是否为空?根据这个答案,没有办法做到这一点。但可能在过去 2 年发生了一些变化。

有没有其他方法可以解决此问题并保持 snapshotListener 到位?

标签: iosswiftasynchronousgoogle-cloud-firestoregrand-central-dispatch

解决方案


现在我实施了某种解决方案 - 使用计数器。我不认为这是最好的解决方案,但至少现在可以工作。

// Get active sessions for each table.
// Run completion only when the last one is processed.
var counter = tables.count

for table in tables {
    DBQuery.getActiveTableSessionAsync(forTable: table, completion: { (tableSession, error) in
        if let error = error {
            completion([], error)
            return
        }
        table.tableSession = tableSession

        counter = counter - 1
        if (counter <= 0) {
            completion(tables, nil)
        }
    })
}

推荐阅读