Sunday, August 24, 2008

Simple iPhone image loader class uses NSThread and NSData dataWithContentsOfURL.

This class, APSSimpleWebImageView, extends the UIImageView class with the method
- (void) loadStringURL:(NSString*)url.

loadStringURL takes the URL of the image you wish to load and loads that image asynchronously.
Download Example Code Here

Create an APSSimpleWebImageView as you would a normal UIImageView and then
invoke loadStringURL with the NSString url of the image you wish to load as follows:
APSSimpleWebImageView* myImageView = [[APSSimpleWebImageView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[myImageView loadStringURL:@"http://example.com/image.jpg"];

(For the complete code listing download the example code.)

Following are a few points of interest from the sample code:
  • (onLoadSuccess andonLoadFailure are optional call backs that can be used to receive notification that the image has appeared.)


  • To load asyncrounsly we invoke NSData dataWithContentsOfURL on a new thread, using NSThread detachNewThreadSelector.

    [NSThread detachNewThreadSelector:@selector(performAsyncLoadWithURL:)
    toTarget:self withObject:[NSURL URLWithString:urlString]]


  • We must create an autrelease pool in performAsyncLoadWithURL: to prevent the new thread from leaking. (Each thread must have an autorelease pool.)

  • performAsyncLoadWithURL: will then block its thread as it performs the image load:
    NSData* imageData = [NSData dataWithContentsOfURL:url options:NSMappedRead error:&loadError];

  • Finally after the image has loaded, we will invoke our load complete call back on the main thread
    [self performSelectorOnMainThread:@selector(loadDidFinishWithError:)
    withObject:loadError waitUntilDone:YES];


    Notice waitUntilDone:YES causes our loading thread to block while the approprate loadDidFinish method is invoked on the main thread. This prevents our imageData object from getting released by the autorelease pool that will be drained in the last line of performAsyncLoadWithURL.

Download Example Code Here



0 Comments:

Post a Comment

<< Home