1

Right now, my code will get the data async and append it to an dictionary (my UserModel)

UserAPI:

// Get all Users
func allUser (completion: @escaping (UserModel) -> Void) {

    let db = Firestore.firestore()
    let docRef = db.collection("users")
    docRef.getDocuments { (querySnapshot, err) in
        for document in querySnapshot!.documents {
            let dic = document.data()
            let user = UserModel(dictionary: dic)
            completion(user)
        }
    }
}

In my ViewController:

UserApi.shared.allUser { (user) in
        self.users.append(user)
        self.tableViewUsers.reloadData()
    }

I am trying to change my approach and want to load ALL the data which I have in my dictionary. I tried this, with a DispatchGroup (I have no experience with DispatchGroups, but googled it):

UserAPI: Tried with Dispatch Group

// Get all Users
func allUser (completion: @escaping ([UserModel]) -> Void) {

    let dispatchGroup = DispatchGroup()
    var model = [UserModel]()

    let db = Firestore.firestore()
    let docRef = db.collection("users")
    docRef.getDocuments { (querySnapshot, err) in

        for document in querySnapshot!.documents {
            dispatchGroup.enter()
            print("disp enter")
            let dic = document.data()
            model.append(UserModel(dictionary: dic))
            dispatchGroup.leave()
            print("disp leave")
        }
    }
    dispatchGroup.notify(queue: .main) {
        completion(model)
        print("completion")
    }
}

With this code, the completion handler gets called first, which is obviously not what I want.

What do I need to fix to load all the data at once?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
JohnDole
  • 525
  • 5
  • 16

1 Answers1

2

You only need to enter and leave the dispatch group once for each asynchronous operation. Since (as far as I can see) you only have one getDocuments call, you should only call enter and leave once.

So something like:

let dispatchGroup = DispatchGroup()
var model = [UserModel]()

let db = Firestore.firestore()
let docRef = db.collection("users")
dispatchGroup.enter()
docRef.getDocuments { (querySnapshot, err) in

    for document in querySnapshot!.documents {
        let dic = document.data()
        model.append(UserModel(dictionary: dic))
    }
    dispatchGroup.leave()
}
...
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807