Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS, NSURLConnection: Delegate Callbacks on Different Thread?

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

like image 832
gngrwzrd Avatar asked Nov 22 '11 02:11

gngrwzrd


1 Answers

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.

like image 114
danyowdee Avatar answered Nov 07 '22 05:11

danyowdee