NSURLConnection & GDC

by

Using NSURLConnection combined with GCD for the first time and noticed that if you invoke NSURLConnection on anything other than the main queue it seems to lock up and nothing happens.  Actually something happens but your delegate never gets called.  Easy fix though; you just need to set the delegate queue (or run loop) before starting the download.

 

Here’s some sample code setting the delegate queue for you to play with if you like. Just make a sample cocoa app from the standard template and then setup the application delegate like this


@interface AppDelegate ()
  @property (strong) NSURLConnection* connection;
  @property (strong) NSMutableData * downloadedData;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
  // Insert code here to initialize your application

  dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), 
   ^{  
      self.downloadedData = [NSMutableData new];
      NSURLRequest * request = [NSURLRequest requestWithURL: 
      [NSURL URLWithString: @"http://wp.me/av6Bm-pZ"]];
      self.connection = [[NSURLConnection alloc] initWithRequest: request 
                          delegate: self 
                        startImmediately: NO];  // This *must* be "NO". 
                                                // Can't switch delegate queue 
                                                // after download starts
      [self.connection setDelegateQueue: [NSOperationQueue mainQueue]];  // *** set queue
      [self.connection start];   // *now* you can start the fetch
      NSLog(@"request queued!");
   });
}

// delegate calls just so let us know when it's working or when it isn't

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog( @"download failed with an error: %@, %@", 
        error, [error description] );

    // release this stuff, test is done.
    self.connection = nil;
    self.downloadedData = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog( @"connection did receive response: %@", response );
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"download data received %lu", [data length] );
    [self.downloadedData appendData: data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"didFinishLoading.  total data is: %lu", [self.downloadedData length] );

    // release this stuff, test is done.
    self.connection = nil;
    self.downloadedData = nil;
}

@end

Line 22 is the key (the setDelegateQueue: call). If you leave that line out then you’ll wonder why it’s not downloading your data. If you change the queue passed to line 12 with dispatch_get_main_queue() then it’ll work without the setDelegateQueue: call).

Obvious once you see it but maybe this’ll save someone a bit of time.

P.S. This was done with Xcode 5 under 10.8.5 fwiw.

Advertisements

Tags: ,

One Response to “NSURLConnection & GDC”

  1. Dad Says:

    Initial tests make it seem like NSURLDownload has the same issue but lacks the necessary setDelegateQueue: option… :-/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: