ceperry
ceperry

Reputation: 520

Using NSURLConnection to make asynchronous requests serially

I'm writing an iPhone app that interacts with a RESTful web service, and I need to request an authentication token for use with all later requests. I want to avoid multithreading if possible and instead use the asynchronous NSURLConnection methods to ensure that the main thread doesn't block (and thereby ensure that the user interface remains responsive).

The problem I'm running into is that I can't figure out how to make the later requests wait for the token to be fetched without making the token fetch a synchronous request and blocking the main thread.

It's occurred to me that I could toss in a loop with a semaphore value that's set when the token fetch completes, but that seems clumsy and the wrong way to do it. Is there an accepted way of doing this correctly?

Upvotes: 2

Views: 471

Answers (2)

Ashley Mills
Ashley Mills

Reputation: 53082

If you're building for iOS 5.0 or later, you can use:

+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]

Make your subsequent call in the completionHandler: block.

Upvotes: 4

Rob Napier
Rob Napier

Reputation: 299265

You may want to look at MKNetworkKit. With some minor tweaking, you should be able to configure it to freeze the queue until the token comes back, at which point you can use addHeaders: to modify the existing operations in the queue to include the auth token. "Freezing" is one of MKNK's major features. It allows you to keep making requests even though you're offline, and they'll be sent once a connection is made.

Upvotes: 1

Related Questions