首页 > 解决方案 > How can I count the documents from a firestore query in swift?

问题描述

The answer must be staring at me but I can't see it. I am trying to query firestore and to get the number of documents it identifies so that I may feed that into my TableView (number of rows) function. Somehow the counter works inside the for loop and I would expect the variable to hold that incremented value but it reverts back to zero when I pass it back. Is it a scope issue ? What am I missing ? here is my code:

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)
}

标签: iosarraysswiftfirebasescope

解决方案


Its async function so you need to return completion handler

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)
                }

    }

}

How to use

runQueryForNumberOfGames {[weak self] (counter) in
    if let count = counter  {
        print(count)
    }
}

推荐阅读