2

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 getRequestToken is never being called as long as getRequestToken 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.

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
  • 2
    How would it prevent flow from moving on; wouldn't it repeatedly re-send the request? – trojanfoe Jan 19 '13 at 16:27
  • There's more to the code than what I've shown here. I've updated the snippet to hopefully be more clear. –  Jan 19 '13 at 16:30
  • 1
    If you want to wait for response in this thread why using asynchronous request? – hoha Jan 19 '13 at 16:32

1 Answers1

5

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.

See:

And lots of others...

Community
  • 1
  • 1
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Don't artificially pump anything; `while(...)` style polling loops are very much to be avoided. – bbum Jan 19 '13 at 16:42