squarefrog
squarefrog

Reputation: 4822

How can I chain asynchronous NSURLConnections?

What would be the most appropriate way to chain asynchronous NSURLConnections? For example, I need to register a user with a web service. The workflow would be as follows: Get Register Token => Use token to Register => Get Login Token => Use token to Login.

I know how to create an asynchronous NSURLConnection, but I'm unsure how to make sure the previous connection has finished before moving on. I know I can achieve this using NSURLConnection sendSynchronousRequest but I don't like my main thread being blocked while these chained requests happen.

Upvotes: 0

Views: 452

Answers (3)

shein
shein

Reputation: 1844

We did EXACTLYA this when we built our first version of SignMeOut for iPhone. We created a subclass of NSUrlconnection and gave it an identifying tag do in the connectionDidFinish you would be able to use a simple switch/case with an enum. Works great - you can see the whole flow and example and code in our blog

http://www.isignmeout.com/multiple-nsurlconnections-viewcontroller/

UPDATE

I've modified the NSURLConnection subclass into a much simpler Category. Most of the usage is the same but cleaner using the same class

https://github.com/Shein/Categories

Upvotes: 2

Andrea
Andrea

Reputation: 26385

You have different options:

  • create a queue using a mutable array or dictionary
  • create an NSOperationQueue kind of easy if you use it in combination with the new only ios5 API for NSUrlConnection
  • third parties lib such as AFNetworking
  • Block GCD grouping them (hard for NSRunLoop reasons, pay attention in wich thread the connection is running in)

Upvotes: 1

tipycalFlow
tipycalFlow

Reputation: 7644

You can look at connectionDidFinishLoading to start another asynchronous connection. For the conditions as to which connection ended, you can keep references to the connections in case other connections are also expected to finish(probably not needed in your case). Make your class follow the NSURLConnectionDelegate and fire the appropriate connections in the connectionDidFinishLoading delegate method. You can also use the connectionDidReceiveData: method to check for credentials, etc received from the service. Go through the documentation too.

Upvotes: 1

Related Questions