4

I directly open URL image in Imageview but i want to store the images in cache memory for future reference... help me to solve my problem..

Thanks in advance

Jignesh B
  • 490
  • 7
  • 18

3 Answers3

5

You can use SDWebImage which uses image caching...

This library provides a category for UIImageVIew with support for remote images coming from the web.

It provides:

An UIImageView category adding web image and cache management to the Cocoa Touch framework

An asynchronous image downloader

An asynchronous memory + disk image caching with automatic cache expiration handling

A background image decompression

A guarantee that the same URL won't be downloaded several times

A guarantee that bogus URLs won't be retried again and again

A guarantee that main thread will never be blocked

Performances! Use GCD and ARC

DD_
  • 7,230
  • 11
  • 38
  • 59
BhushanVU
  • 3,455
  • 1
  • 24
  • 33
0

It's a classic problem in iOS development, I write a class OnlineImageView before, which is using NSOperationQueue -- Now GCD maybe better.

You wanna access an online image:

  1. First, you try to hit the image (with the key, maybe url) in the memory cache, but missed.
  2. Second, you try to find the image in the disk, missed again.
  3. Then, you should download the online image asynchronously, using GCD or some other methods.
  4. When the image is downloaded successfully, show it in the UIImageView, and cache it in the memory, write it down to the disk for future use.

Some sample code :

- (void)downloadImage:(NSDictionary *)info
{
    /* HOWTO: Prevent Downloading the same url many times */
    /* Keep the download task one by one ? */

    NSString *url = [info objectForKey:@"url"];
    NSURL *imageUrl = [NSURL URLWithString:url];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];

    if (image) {
        id theDelegate = [info objectForKey:@"delegate"];
        if ([theDelegate respondsToSelector:@selector(imageDownloader:didFinishWithImage:)]) {
            [theDelegate imageDownloader:self didFinishWithImage:image];
        }

        [cacheQueue cacheImage:image withKey:url];
    } else {
#ifdef DEBUG
        NSLog(@"Failed to download : %@\n", url);
#endif
    }
}
Jason Lee
  • 3,200
  • 1
  • 34
  • 71
0

Use SDWebImage . its best and easy for image data caching.

DD_
  • 7,230
  • 11
  • 38
  • 59
Monish Bansal
  • 509
  • 3
  • 15