0
votes

I'm loading certain images from a certain server asynchronously. I'm firing a number of requests at once using NSURLConnection connectionWithRequest method and receive the data using NSURLConnectionDelegate didReceiveData.

At didReceiveData, how do I know which request this data matches? At didReceiveResponse I can use the URL method of the response given as a parameter, but in didReceiveData I only have the received data.

It seemed like the perfect answer would be to use NSURLConnection sendAsynchronousRequest, as the completion handler has all the required parameters: (NSURLResponse*, NSData*, NSError*). I can use [response URL] to make a match to the original request... except in one case: not all the images I try to download exist. In that case, the request is redirected to a generic error page and the URL of that generic page is received, so I can't match the response to a request I've made. This I could handle with connectionWithRequest, but I can't get the best of both worlds.

2

2 Answers

0
votes

In

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

you can use

NSURLRequest *request = [connection originalRequest];

to get the request that the connection was started with.

(This method is available since iOS 5.0, but I could not find it in my Xcode iOS 5.1 Library. You find it in the iOS 6 Library, in the header file NSURLConnection.h or here: http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURLConnection/originalRequest).

More methods to manage multiple connections can be found in this thread: Managing multiple asynchronous NSURLConnection connections.

If you use sendAsynchronousRequest:queue:completionHandler: then you can just use the request parameter in the completion block.

0
votes

At connection:didReceiveData: the first parameter is the NSURLConnection instance. So I don't understand where the problem is. You create a connection, then you send a request to that connection and the delegate receive the connection:didReceiveData with the connection value.

If you are using the same delegate for all the request you have to check the connection so you can say which request is associated to.

Perhaps you have to maintain a table of connection/request pairs.