Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to send a series of HTTP requests with NSURLConnection

HTTP requests made with NSURLConnection are event driven. This makes things a little weird when you need to issue say three requests one after another, where each request uses information returned by the previous one.

I'm used to doing it like this:

response1 = request1();
response2 = request2(response1);
response3 = request3(response2);

But the only way I could find how to do this with NSURLConnection is to have connectionDidFinishLoading: make the next request. But when the number of sequential requests grows, this can get messy.

What's the idiomatic way to handle sequential HTTP requests with cocoa?

like image 209
pepsi Avatar asked May 11 '12 16:05

pepsi


1 Answers

You could wrap the requests in an NSOperation and then define operation dependencies, so that each request must wait on its dependent requests before executing.

From the Apple Docs:

Dependencies are a convenient way to execute operations in a specific order. You can add and remove dependencies for an operation using the addDependency: and removeDependency: methods. By default, an operation object that has dependencies is not considered ready until all of its dependent operation objects have finished executing. Once the last dependent operation finishes, however, the operation object becomes ready and able to execute.

like image 97
tronbabylove Avatar answered Nov 02 '22 18:11

tronbabylove