Programming

NSURLConnection, background threads/NSOperationQueue with Facebook Connect


In one project I had a serialised GCD queue to execute web service calls on, which I did using NSURLConnection in synchronous mode. I then had a background call I wanted to do where I was calling the FBConnect library to upload a photo (uses an FBRequest) underneath. I thought that it might be useful to perform this call in a block that was running on an NSOperationQueue as the UI didn’t need to update or wait for this operation in any way. It turns out this doesn’t work. Why? Because, digging into the FBConnect source code, the FBRequest uses NSURLConnection in its standard (asynchronous) mode. When I put breakpoints on the connectionDidFinishLoad and connectionDidReceiveError delegate methods, none were ever getting called. According to documentation this should be impossible. I at first thought it must be a long timeout. Sure enough, facebook are setting a timeout of 180 seconds, which is huge. So I waited to see if it was just timing out but it wasn’t. Finally I realised that NSURLConnection is probably only allowed on the main thread if running asynch. Since I don’t have control over how FBRequest does it’s NSURLConnection calls (short of editing FB source code, which I am avoiding for maintenance reasons), I decided to put the call back on the main thread using dispatch_async(dispatch_get_main_thread,^{}); and it worked. The delegate functions are now called as usual.

Advertisements

3 thoughts on “NSURLConnection, background threads/NSOperationQueue with Facebook Connect

  1. I had the same problem with the Dropbox library and NSMetadataQuery (for iCloud)… Seriously, there should be a big warning for this somewhere in the documentation of NSMetadataQuery.

    I’m curious, did you find any mention of this in the documentation? From random experiments I reached the same conclusion as you, but is this a normal thing? Are we really expected to know which calls use asynchronous NSMetadataQuery and make sure to throw all such calls on the main thread?

    And on an unrelated note, this hit should have really been on the first page in google…

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