Search code examples
iosimagecachingsdwebimage

How to use SDWebImage to cache image for multiple sized images


From my web service i am getting multiple sized images. I m loading them in TableView. When i m loading them new images which haven't cached yet flickers between placeholder and original image, or sometimes the image appear as smaller than the usual size. But just a bit scrolling down or up actually fix the problem but i want them to be at original size from the beginning. But it would appear in original shape from the next time i suppose because the picture was already cached

Initially

Initial

After a bit scrolling

enter image description here

My code in cellForRowAtIndexPath:

[cell.image sd_setImageWithURL:[NSURL URLWithString:[NSMutableString stringWithFormat:@"%@app/media/access/pictures?p=%@",baseurl,data.picPath]]
                 placeholderImage:[UIImage imageNamed: @"image_loader.gif"]];

then in heightForRowAtIndexPath:

NSURL *filePath = [NSURL URLWithString:[NSMutableString stringWithFormat:@"%@app/media/access/pictures?p=%@",baseurl,data.picPath]];

        NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:filePath];
        UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
        self.img = image;



        if (self.img.size.width > CGRectGetWidth(self.view.bounds)) {
            CGFloat ratio = self.img.size.height / self.img.size.width;
            return CGRectGetWidth(self.view.bounds) * ratio+140;
        } else {

            return self.img.size.height+180;
        }

I have visited https://github.com/rs/SDWebImage and in their common problem section they have mentioned about the problem but the suggested solution didn't work for me!!!


Solution

  • Actually what i did, i checked if the image was cached already and if not i have downloaded it asynchronously under heightForRowAtIndexPath:

    if(image != NULL)
            {
            self.img = image;
            }
            else
            {
                SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
                [downloader downloadImageWithURL:filePath
                                         options:0
                                        progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                            // progression tracking code
                                        }
                                       completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                                           if (image && finished) {
                                               // do something with image
    
                                               self.img = image;
    
                                           }
                                       }];
    
            }