I have a ton of repeating code in my class that looks like the following:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
The problem with asynchronous requests is when you have various requests going off, and you have a delegate assigned to treat them all as one entity, a lot of branching and ugly code begins to formulate going:
What kind of data are we getting back? If it contains this, do that, else do other. It would be useful I think to be able to tag these asynchronous requests, kind of like you're able to tag views with IDs.
I was curious what strategy is most efficient for managing a class that handles multiple asynchronous requests.
in iOS5 and above you can just use the class method
sendAsynchronousRequest:queue:completionHandler:
No need to keep track of connections since the response returns in the completion handler.
I have a project where I have two distinct NSURLConnections, and wanted to use the same delegate. What I did was create two properties in my class, one for each connection. Then in the delegate method, I check to see if which connection it is
This also allows me to cancel a specific connection by name when needed.
Subclassing NSURLConnection to hold the data is clean, less code than some of the other answers, is more flexible, and requires less thought about reference management.
Use it as you would NSURLConnection and accumulate the data in its data property:
That's it.
If you want to go further you can add a block to serve as a callback with just a couple more lines of code:
Set it like this:
and invoke it when loading is finished like this:
You can extend the block to accept parameters or just pass the DataURLConnection as an argument to the method that needs it within the no-args block as shown
THIS IS NOT A NEW ANSWER. PLEASE LET ME SHOW YOU HOW I DID
To distinguish different NSURLConnection within same class's delegate methods, I use NSMutableDictionary, to set and remove the NSURLConnection, using its
(NSString *)description
as key.The object I chose for
setObject:forKey
is the unique URL that is used for initiatingNSURLRequest
, theNSURLConnection
uses.Once set NSURLConnection is evaluated at
Every NSURLConnection has an hash attribute, you can discriminate all by this attribute.
For example i need to mantain certain information before and after connection, so my RequestManager have an NSMutableDictionary to do this.
An Example:
After request:
Try my custom class, MultipleDownload, which handles all these for you.