Chris Wilson Chris Wilson - 1 year ago 93
Objective-C Question

Completion handler not being called when containing function is within a while loop

I have the following code:

while ( /* Some condition that will not be met in this example */ ) {
if( shouldSendRequest ) {
[launchpad getRequestToken];
else {
// Next step

- (void)getRequestToken {

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

[self requestForRequestTokenDidComplete:data withResponse:response withError:error];

-(void)requestForRequestTokenDidComplete:(NSData *)data
withResponse:(NSURLResponse *)response withError:(NSError *)error {
// Deal with the returned token

The problem I have is that the completion handler in
is never being called as long as
is inside the while loop. As soon as I comment out the while loop, everything works.

What's happening here and is it possible to prevent it? I has planned to use the while loop to prevent the flow of execution moving on before this (and other) completion handlers had finished doing their thing.

Answer Source

The reason it's not working is because NSURLConnection works along with the runloop to perform the async request. Therefore if you stop the runloop by halting flow within the while statement you are preventing the request from completing.

You will need to artificially pump the runloop or use a background thread.


And lots of others...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download