iOS, NSURLConnection: Delegate Callbacks on Different Thread?

gngrwzrd picture gngrwzrd · Nov 22, 2011 · Viewed 9.3k times · Source

How can I get NSURLConnection to call it's delegate methods from a different thread instead of the main thread. I'm trying to mess around with the scheduleInRunLoop:forMode:but doesn't seem to do what I want.

I have to download a large file and it interrupts the main thread so frequently that some rendering that is happening starts getting choppy.

NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
NSRunLoop * loop = [NSRunLoop currentRunLoop];
NSLog(@"loop mode: %@",[loop currentMode]);
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[connection start];

The other thing I don't see much of is "Modes" There are only two modes documented so not much really to test with.

Any ideas?

Thanks

Answer

danyowdee picture danyowdee · Dec 26, 2011

There are several options:

  1. In your implementation of the delegate methods, make use of dispatch_async.
  2. Start the schedule the connection on a background thread.

You can do the latter like this:

// all the setup comes here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSRunLoop *loop = [NSRunLoop currentRunLoop];
    [connection scheduleInRunLoop:loop forMode:NSRunLoopCommonModes];
    [loop run]; // make sure that you have a running run-loop.
});

If you want a guarantee on which thread you're running, replace the call to dispatch_get_global_queue() appropriately.