1

I'm trying to run a download in a background thread as to not block the main UI thread on iOS, what I did was create a new thread using

[NSThread detachNewThreadSelector:@selector(startDownload) toTarget:downloadObject withObject:nil];

Then the following code runs on a background thread:

NSURL* urlForCalendar = [NSURL URLWithString:@"http://www.apple.com/"];

urlRequest = [NSURLRequest requestWithURL:urlForCalendar];
urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:NO];

NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[urlConnection scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
[urlConnection start];

However, the delegate callbacks are never called.

EDIT: For anyone who might come across a similar problem in the future, after a bit of trying to figure out why it wasn't working, I wasn't running the loop. So the last 3 lines of code should actually be:

NSRunLoop* runLoop = [NSRunLoop currentRunLoop];   
[urlConnection scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
[urlConnection start];
[runLoop run];
user3791979
  • 60
  • 2
  • 8
  • The reason I'm not using the [NSURLConnection sendAsynchronousRequest...] is because I want to use the delegate methods for NSURLConnection as they provide a lot of flexibility – user3791979 Jul 29 '14 at 19:55
  • Are you sure you keep thread alive for the time of download? – PiotrDomo Jul 29 '14 at 20:00
  • 1
    You don't need to run on a background thread with NSURLConnection. The download is on a background thread already, but the delegate methods will run on the thread you created the connection in (which should be the main thread). You don't need to mess around with run loops or threads, unless the processing of the return result itself is slow enough that it needs to be in the background. – rdelmar Jul 29 '14 at 21:02

1 Answers1

3

You don't run the run loop of the thread you created, so the connection you add to the run loop is never serviced and you never get any callbacks.

Generally you just want to handle the callbacks on the main thread and then push the result to a background thread if heavy processing is required.

You can do what you're currently doing though so long as you run the run loop and tidy up properly once the download is complete.

Wain
  • 118,658
  • 15
  • 128
  • 151