The situation is I need to loop through multiple objects and make a network call on each.
After all of the network calls are finished, I will call my completion block with all of the data that I collected from these network calls.
To accomplish this, I am attempting to use a dispatch group, entering when the network call begins and leaving when it is finished:
for user in users { dispatch_group_enter(downloadGroup) UserManager.retrieveFriendsForUser(user, completed: { (usersFriends, fault) in guard let usersFriends = usersFriends else { return } dispatch_group_leave(downloadGroup) }) } I am then waiting for them to finish with the following:
dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER); However, it does not seem to wait for all of my grouped network calls to finish.
Here is all of the code in complete context; I am looping through many users and then querying for their friends. And I want the method to return all of their friends combined (by concatenating all the results to the allNonFriends array):
class func retrieveNonFriendsOfFriends(completed : (users : [BackendlessUser]?, fault : Fault?) -> Void) { var allNonFriends = [BackendlessUser]() let downloadGroup = dispatch_group_create() // 2 dispatch_group_enter(downloadGroup) // 3 UserManager.retrieveCurrentUsersFriends { (users, fault) in guard let users = users else { print("Server reported an error: \(fault)") completed(users: nil, fault: fault) return } for user in users { dispatch_group_enter(downloadGroup) // 3 UserManager.retrieveFriendsForUser(user, completed: { (usersFriends, fault) in guard let usersFriends = usersFriends else { print("Server reported an error: \(fault)") return } let nonFriends = usersFriends.arrayWithoutFriends(users) allNonFriends += nonFriends dispatch_group_leave(downloadGroup) // 4 }) } } dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER); completed(users: allNonFriends, fault: nil) }
guardcases. Have you tried adding print statements to see what order things are happening in? How many results do you get inallNonFriends?