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];
}