Reputation:
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.
Upvotes: 2
Views: 1280
Reputation: 122391
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...
Upvotes: 5