How do I properly query Firestore database in swift using dispatch group

Viewed 292

I am trying to query my firestore database and count the number of times a field is set to pre-defined enum. However, when I run it or step through it with a breakpoint, the closure never returns and my dispatch.wait() hangs forever. I am not sure why the query isn't working, as the collection exists and I have test data in there for this query. I am also able to read and write to the evaluations collection so I don't think it is a permissions issue.

I would expect at least to get an error if the query failed but it just skips over it and hangs on the wait until I stop the run.

    let user = self.user
    let evalRef = self.db.evaluations(forUser: user.userID)

    let dispatchGroup = DispatchGroup()
    for keys in self.stat.enumCases.keys {
        dispatchGroup.enter()
        evalRef.whereField(self.stat.queryName, isEqualTo: keys).getDocuments { (querySnapshot, err) in
            if let err = err {
                print(err.localizedDescription)
                dispatchGroup.leave()
                return
            }
            guard let querySnapshot = querySnapshot else {
                //error
                dispatchGroup.leave()
                return
            }
            guard let enumCaseName = self.stat.enumCases[keys] else {
                //error
                dispatchGroup.leave()
                return
            }
            if querySnapshot.count > 0 {
                self.stat.primaryStatStruct[keys] = primaryStatForEachCase(enumCaseTitle: enumCaseName, enumCaseValue: Double(querySnapshot.count))
                dispatchGroup.leave()
            } else {
                self.stat.primaryStatStruct[keys] = primaryStatForEachCase(enumCaseTitle: enumCaseName, enumCaseValue: 0.0)
                dispatchGroup.leave()
            }
        }
    }
    dispatchGroup.wait()

Here are other snippets to give a better picture:

  /// Returns a reference to the user evaluation collection.
  func evaluations(forUser userID: String) -> CollectionReference {
    return self.collection("users/\(userID)/evaluations")
  }

print of keys and self.stat.queryName

evaluations collection with documents

document data matching keys and queryName

Any help would be greatly appreciated.

0 Answers
Related