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;

}

tips & tricks

Join 7,719 other subscribers

interview questions


Algorithm Android Android Studio API APP Programming Apps blogging Browser CheatSheets Code Config CSS DATABASE dsa error Features HTML HTML5 IDE installation Interview Questions IOS iPhone javascript Mac objective-c OneDrive OS Placeholder Programming quicktips SDK SEO Settings SMO SQL swift swiftUI Teams Tips & Tricks Tools UI Web Wordpress Xcode


Archives

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from CODE t!ps

Subscribe now to keep reading and get access to the full archive.

Continue reading