Best way to send a series of HTTP requests using NSURLConnection

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

I'm used to doing it like this:

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

But the only way to find a way to do this with NSURLConnection is to make connectionDidFinishLoading: make the following request. But when the number of consecutive requests grows, it can become messy.

What is the idiomatic way to handle consecutive HTTP requests with cocoa?

+6
source share
3 answers

You can wrap queries in NSOperation and then define the dependencies of the operations so that each query must wait for its dependent queries before executing.

From Apple Docs :

Dependencies are a convenient way to perform 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 its dependent operational objects have completed execution. However, as soon as the last dependent operation completes, the work object becomes ready and can complete.

+7
source

I would advise you to use a third-party library called MKNetworkKit . It can handle the hard work for you, so you can focus on key aspects of your application. You can find it here .

0
source

You can and should use NSOperation and NSOperationQueues .

A good tutorial can be found here: How to use NSOperations and NSOperationQueues

0
source

Source: https://habr.com/ru/post/915514/


All Articles