Search code examples
iphoneios6

Show activity indicator with lazy loading using AsyncImageView classes


I am using AsyncImageView classes to apply lazy loading on UITableView. And want to apply activity indicator on image view until the image is loaded on cell. Below is my code i am trying.

//  AsyncIamgeView.m

 - (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {

//[connection release];
UIActivityIndicatorView     *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
indicator.center = CGPointMake(15, 15);

connection=nil;

if ([[self subviews] count]>0) {
    [[[self subviews] objectAtIndex:0] removeFromSuperview];
}

UIImage *imgData = [UIImage imageWithData:data];
UIImageView* imageView = [[UIImageView alloc]init];
 [imageView addSubview:indicator];
[indicator startAnimating];

    if(imgData == nil)
{
    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NoImagenew.png"]];
    //[indicator stopAnimating];
}
else{
    imageView = [[UIImageView alloc] initWithImage:imgData];
   // [indicator stopAnimating];
}
//imageView.contentMode = UIViewContentModeScaleAspectFit;
//imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth || UIViewAutoresizingFlexibleHeight );
//[imageView sizeToFit];
[self addSubview:imageView];

imageView.frame = self.bounds;
//imageView.frame = CGRectMake(0, 0, 85, 94);
[imageView setNeedsLayout];
[self setNeedsLayout];
//[data release];
data=nil;
}

 //   cellForRowAtIndexPath method.

 asyncImageView = [[AsyncImageView alloc]initWithFrame:CGRectMake(1, 3, 85, 54)];
[asyncImageView loadImageFromURL:[NSURL URLWithString:imageUrlString]];
[cell.contentView addSubview:asyncImageView];

This code shows activity indicator but when image is loaded after that not before loading images. Please guide for above.


Solution

  • Currently you are adding activity indicator when your image is downloaded.

    Here is the simple idea, hope you can implement this in your code

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
       // This method is called when your connection receives a response
       // add your activity indication here and start animating
    }
    
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
      // This method is called when your image is downloaded.
      // remove your activity indicator or stop animating here
    }