I've got a bunch of server requests which I can run asynchronously, but I need to wait for them all to finish before I continue.
dispatch_group_async and it seems quite reasonable, but I can't get it to work. It either blocks forever or doesn't block at all. My latest attempt looks something like....
dispatch_group_t group;
- (void)cleanRoom {
NSAssert(![NSThread isMainThread], @"not on main thread.");
group = dispatch_group_create();
for (Junk *thing in myRoom) {
// take it off the current thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// register code against group
dispatch_group_enter(attachmentGroup);
NSURLConnectionWrapper *wrapper = [[NSURLConnectionWrapper alloc] init];
wrapper.delegate = self;
[wrapper sendRequestFor:thing];
}];
}
// wait till the stuff is the group is done
dispatch_group_wait(attachmentGroup, DISPATCH_TIME_FOREVER);
NSLog(@"waiting complete!!!!");
// process the results now that I have them all
}
- (void)wrapperConnectionDone {
// do a bit more junk
dispatch_group_leave(group);
}
This causes it to block forever because NSURLConnectionDelegate
and NSURLConnectionDataDelegate
methods are never getting called. I'm assume I've somehow block their thread, but using NSLog
I can confirm the NSURLConnection
is on a different thread than my cleanRoom
method.
I read a bit about other threads not having run loops to make the callbacks, so I've tried things like connection setDelegateQueue:[NSOperationQueue mainQueue]]
and [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]]
but to no noticable effect.
+ sendAsynchronousRequest:queue:completionHandler:
doesn't work for me, I've got some ugly authentication. I've seen some good example with that, but I've failed at adapting.
I'm obviously missing some fundamental bit, but I can't find it.