Quote:
Originally Posted by Dutch
This is how I do it. This is asynchronous so it will not tie up the main thread.
.h file
Code:
NSURLConnection *connection;
NSMutableData* data;
UIImage *image;
YourParentViewController *myParentController ;
-(void)startDownload:(NSString *)url withParentController:(YourParentViewController *)parent;
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, retain) NSMutableData* data;
@property (nonatomic, retain)UIImage *image;
@property (nonatomic, retain) YourParentViewController *myParentController;
.m file
Code:
-(void)startDownload:(NSString *)url withParentController:(YourParentViewController *)parent{
[self setMyParentViewController:parent];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
if (data==nil) data = [[NSMutableData alloc] initWithCapacity:2048];
[data appendData:incrementalData];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
[self setImage: [UIImage initWithData:data]];
[myParentController processImage:[self image]];
data=nil;
}
you would probably want to put this code in its own object (called for example DownloadImage). then you can download the images like this:
Code:
-(void)downloadTwoImages{
//Make this a property somewhere in your H file.
if (! imagesArray) imagesArray=[[NSMutableArray alloc] init];
[imagesArray removeAllObjects];
DownloadImage *imageDownloader=[[[DownloadImage alloc] init] autorelease];
[imageDownloader startDownload:@"http://yourdomain/image1.png" withParentController:self];
[imageDownloader startDownload:@"http://yourdomain/image2.png" withParentController:self];
}
-(void) processImage:(UIImage *)image{
[imagesArray addObject:image];
}
|
With the approach you are using for multiple images, are you able to control the order in which they are added to the array? From looking at this code, it looks like the first one to finish downloading will be added to the array, even if it was the second one called. I'm struggling to figure out how to load multiple images one after each other using NSURLConnection. I can download one image no problem using NSURLConnection, but the right way to fire off multiple downloads for 3-4 images isn't clear to me.