简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM