如何快速计算Firestore查询中的文档?

时间:2020-05-28 20:23:52

标签: ios arrays swift firebase scope

答案肯定盯着我,但我看不到。我正在尝试查询firestore并获取它标识的文档数,以便可以将其输入到TableView(行数)函数中。计数器以某种方式在for循环内工作,我希望变量保存该递增的值,但是当我将其传递回时,它将恢复为零。这是范围问题吗?我想念什么?这是我的代码:

func runQueryForNumberOfGames() -> Int {
    var counter = 0
    // query the games for the user who is logged into app
    let currentUid = Auth.auth().currentUser!.uid

    db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
               if let err = err {
                print("error getting documents: \(err)")
                return
               }
               else {

                    for document
                        in querySnapshot!.documents {
                        print(document)
                        counter += 1
                        print("the counter is: \(counter)")
                    }
                }

    }
    print("the counter outside of the for loop is \(counter)")
    return (counter)
}

1 个答案:

答案 0 :(得分:1)

它的异步功能,因此您需要返回完成处理程序

dllUser32 := syscall.NewLazyDLL("user32.dll")
GetForegroundWindow := dllUser32.NewProc("GetForegroundWindow")
hwnd, _, _ := syscall.Syscall(proc.GetForegroundWindow.Addr(), 0,
    0, 0, 0)

使用方法

func runQueryForNumberOfGames(completion: @escaping (Int?)-> Void) {
    var counter = 0
    // query the games for the user who is logged into app
    let currentUid = Auth.auth().currentUser!.uid

    db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
               if let err = err {
                print("error getting documents: \(err)")
                completion(nil)
                return
               }
               else {

                    for document
                        in querySnapshot!.documents {
                        print(document)
                        counter += 1
                        print("the counter is: \(counter)")
                    }

                completion(counter)
                }

    }

}