I'm trying to get the count of documents where located in Firebase.
Whenever I try to assign the count of documents a variable in closure, the value is null.
According to articles, networking takes some time and it happens asynchronously. So due to asynchronous behaviour, returning a value inside a closure might happen before assignment of the value.
I tried to add dispatchqueue.main.async but it didn't work.
Here is my code
func getEventCount () -> Int? {
var count: Int?
db.collection("Events").whereField("owner", isEqualTo: currentUser.email).getDocuments { (snapshot, error) in
if error != nil {
print(error)
}else {
DispatchQueue.main.async {
if let snapshot = snapshot {
count = snapshot.count
}
}
}
}
return count
}
My main goal is to get count of documents from database and assign a variable called count.