How to optimize the image in SDWebImage

306 views Asked by At

I have a json that contains two images' urls, and I use SDwebimage to load the two images, please look at following code

  NSDictionary *dic = [_arrayDB objectAtIndex:[indexPath row]];
  NSURL *imageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",imageURL, [dic objectForKey:@"oneimageurl"]]];
__block UIActivityIndicatorView *activityIndicator;
__weak UIImageView *weakImageView = cell.oneimage;
[cell.oneimage sd_setImageWithURL:imageUrl placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize){
    if (!activityIndicator) {
        [weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]];
        activityIndicator.center = weakImageView.center;
        [activityIndicator startAnimating];
    }
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    [activityIndicator removeFromSuperview];
    activityIndicator = nil;
}];

NSURL *imageUrl1 = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",imageURL, [dic objectForKey:@"twoimageurl"]]];
__block UIActivityIndicatorView *activityIndicator1;
__weak UIImageView *weakImageView1 = cell.twoimage;
[cell.twoimage sd_setImageWithURL:imageUrl1 placeholderImage:[UIImage imageNamed:@"avatar"] options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize1, NSInteger expectedSize1) {
    if (!activityIndicator1) {
        [weakImageView1 addSubview:activityIndicator1 = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]];
        activityIndicator1.center = weakImageView1.center;
        [activityIndicator1 startAnimating];
    }
} completed:^(UIImage *image1, NSError *error1, SDImageCacheType cacheType1, NSURL *imageURL1) {
    [activityIndicator1 removeFromSuperview];
    activityIndicator1 = nil;
}];

this code runs well, but i think it's so more code, and I want to optimize this code, so can you help me? Many thanks.

2

There are 2 answers

2
Ankit Kumar On

I think SDwebImage not do resizing - you may use this - https://github.com/mustangostang/UIImage-ResizeMagick

you can use easily like -

[cell.twoimage sd_setImageWithURL:imageUrl1 placeholderImage:[UIImage imageNamed:@"avatar"]];

for image2 -

[cell.twoimage sd_setImageWithURL:imageUrl2 placeholderImage:[UIImage imageNamed:@"avatar"]];

just put these line of code in between for speedy download as -

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

    [cell.twoimage1 sd_setImageWithURL:imageUrl1 placeholderImage:[UIImage imageNamed:@"avatar"]];
    [cell.twoimage2 sd_setImageWithURL:imageUrl2 placeholderImage:[UIImage imageNamed:@"avatar"]];

});
0
Jasper On

Since you have two UIImageView's you need to populate with a unique UIImage you will have to use separate code for each UIImageView