I am am trying to get multiple NSURLConnections to run in parallel (synchronously), however if it is not running on the main thread (block of code commented out below) the URL connection doesn’t seem to work at all (none of the NSURLConnection delegate methods are triggered). Here is the code I have (implementation file of an NSOperation subclass):
- (void)start
{
NSLog(@"DataRetriever.m start");
if ([self.DRDelegate respondsToSelector:@selector(dataRetrieverBeganExecuting:)])
[self.DRDelegate dataRetrieverBeganExecuting:identifier];
if ([self isCancelled]) {
[self finish];
} else {
/*
//If this block is not commented out NSURLConnection works, but not otherwise
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
return;
}*/
SJLog(@"operation for <%@> started.", _url);
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
NSURLRequest * request = [NSURLRequest requestWithURL:_url];
_connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
if (_connection == nil)
[self finish];
} //not cancelled
}//start
Ran through it with a debugger, and after the end of this start method none of the NSURLConnection delegates trigger (I set breakpoints there). But on the main thread it works just fine. Any ideas of what’s up? Thanks!
Background threads don’t automatically have an active run loop on them. You need to start up the run loop after you create the
NSURLConnectionin order to get any input from it. Fortunately, this is quite simple:When you say that you are running the connections synchronously, you are incorrect. The default mode of
NSURLConnectionis asynchronous — it creates and manages a new background thread for you, and calls back to the delegate on the original thread. You therefore don’t need to worry about blocking the main thread.If you do actually want to perform a synchronous connection, you would use
sendSynchronousRequest:returningResponse:error:, which will directly return the data. See “Downloading Data Synchronously” for details.