Reputation: 8100
I have an array of URLs which I use to receive associated Images from remote server using NSURLConnection
NSURL *url = [NSURL URLWithString:URLString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest
requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:2.0f];
// Run network request asynchronously
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
in the delegate protocol
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// As chuncks of the image are received, we build our data file
[self.imageData appendData:data];
}
and finally
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// All data has been downloaded, now we can set the image in the images array
_img = [UIImage imageWithData:self.imageData];
[self.imagesArray insertObject:_img atIndex:_index];
[self.imageData setLength:0];
_index = _index+ 1;
}
but the order of received is not always the same as the order of sending URL request I tried using an instance variable index to insert these images in the same order in the images array but that does not always work and I still am getting unordered listings , could anyone point me in the right direction as to how to achieve this.
Upvotes: 0
Views: 123
Reputation: 104
In general if I am downloading images I rely on the excellent AFNetworking classes. http://afnetworking.com This provides the overall behavior you are looking for (one takes a UIImageView, and default image, another will just deliver the image bytes)
If there is a reason that you MUST make your own, then I would have a dictionary of download name to NSURLConnection. This will allow you to then figure out which download has ASYNCHRONOUSLY completed, and act correctly on it.
If you really mean a SYNCHRONOUS delivery of download objects, then dispatch them one at a time, wait for the response, and then start the next on completion.
Upvotes: 0
Reputation: 89509
What I've done in my own implementations is to create a custom Objective-C object which I insert into a mutable array (let's call it a "RemoteImageObject
") which contains both the image data and the URL from which it came from.
What you would do is make the request, create a RemoteImageObject and add the URL to it, add that to your array.
When the request comes back with image data. Go look up your RemoteImageObject in your array and add the image data to it.
And when you want to display the image data, just fetch the imageData for each of those RemoteImageObjects.
Makes sense?
Upvotes: 1