Tips to Loading image from a URL to UIImage object

Tips to Loading image from a URL to UIImage object

Load image pointed by URL, for example, http://mycodetips.com/images/image0.jpg, using NSURL, NSURLRequest, and NSURLConnection

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:

[NSURLRequest requestWithURL:

[NSURL URLWithString:@“http://mycodetips.com/images/image0.jpg”]] delegate:self];

Implement delegate methods of NSURLConnection

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

NSMutableData object can be used store data fragment whenever it is received

self.imageData = [NSMutableData data];

…

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

{

[self.imagedata appendData:data];

}

Sample code

- (void)startDownload

{

self.imageData = [NSMutableData data];

// alloc+init and start an NSURLConnection; release on completion/failure

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:

[NSURLRequest requestWithURL:

[NSURL URLWithString:imageURLString]] delegate:self];

self.imageConnection = conn;

[conn release];

}

- (void)cancelDownload

{

[self.imageConnection cancel];

self.imageConnection = nil;

self.imageData = nil;

}

#pragma mark -

#pragma mark Download support (NSURLConnectionDelegate)

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

{

[self.activeDownload appendData:data];

}- (

void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

// Clear the activeDownload property to allow later attempts

self.imageData = nil;

// Release the connection now that it’s finished

self.imageConnection = nil;

}- (

void)connectionDidFinishLoading:(NSURLConnection *)connection

{

// Set appIcon and clear temporary data/image

UIImage *image = [[UIImage alloc] initWithData:self.imageData];

// Now we have loaded image in ‘image’

// DO WHATEVER WE WAN WITH ‘image’

// call our delegate and tell it that our icon is ready for display

[delegate appImageDidLoad: image];

[image autorelease];

// clean-up

self.imageData = nil;

// Release the connection now that it’s finished

self.imageConnection = nil;

}