1

is there a way to insert images, that are downloaded from the web, to the devices cache? in my application, there's a few views that contains images. at every tableView there's 25-30 images. the problem is that the images are loaded when scrolled, and the result is at scrolling the image takes 2-3 seconds to reload... doesn't look good :) at the moment, i'm using NSURLRequest at each cell.

NSURL* url = [NSURL URLWithString:article.articleImage];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) 
{
     if (!error)
     {
         UIImage* image = [[UIImage alloc] initWithData:data];
                                           MainImg.image = image;
                                           article.articleImg=image;
     }

}];

I've tried to use multi thread, but the launch of the application takes too long. ideas?

Jitendra
  • 4,987
  • 2
  • 21
  • 42
AndroAid
  • 77
  • 1
  • 8
  • See [this][1] question. It explains hoe to save image to cache. [1]: http://stackoverflow.com/questions/9289672/how-to-store-images-in-cache – Durgaprasad Jun 13 '13 at 12:10

4 Answers4

0

Hi you need UIImageView+AFNetworking.h category download and use AFNetworking u are sorted

use its - (void)setImageWithURL:(NSURL *)url method works like charm

amar
  • 4,237
  • 6
  • 38
  • 50
0

You can use NSURLCache for this purpose. Yesterday I've worked with this, and I make class:

@interface MyURLCache : NSURLCache
@property (nonatomic, assign) NSTimeInterval timeAvaiable;
@end

@implementation MyURLCache

- (id)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(NSString *)path
{
    self = [super initWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:path];
    if(self){
        _timeAvaiable = 5*60;//5 мин
    }
    return self;
}
- (id)init
{
    self = [super init];
    if(self){
        _timeAvaiable = 5*60;
    }
    return self;
}

+ (NSCachedURLResponse*)addInfoDataToCachedResponce:(NSCachedURLResponse*)cachedResponse
{
    NSMutableDictionary* newUserInfo = [@{@"LastUpdate" : @([[NSDate date] timeIntervalSince1970])} mutableCopy];
    if([cachedResponse userInfo])
        newUserInfo[@"UserInfo"] = [cachedResponse userInfo];

    return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
                                                    data:[cachedResponse data]
                                                userInfo:newUserInfo
                                           storagePolicy:[cachedResponse storagePolicy]];
}

+ (NSCachedURLResponse*)removeInfoDataFromCachedResponce:(NSCachedURLResponse*)cachedResponse
{
    return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
                                                    data:[cachedResponse data]
                                                userInfo:[cachedResponse userInfo][@"UserInfo"]
                                           storagePolicy:[cachedResponse storagePolicy]];
}

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    NSCachedURLResponse* result = [super cachedResponseForRequest:request];
    NSDate* lastUpdate = [NSDate dateWithTimeIntervalSince1970:[result.userInfo[@"LastUpdate"] doubleValue]];
    BOOL expired = fabs([lastUpdate timeIntervalSinceNow]) > _timeAvaiable;
    return expired? nil : [[self class] removeInfoDataFromCachedResponce:result];
}

- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
    [super storeCachedResponse:[[self class] addInfoDataToCachedResponce:cachedResponse] forRequest:request];
}

@end

And just enable cache when app loaded:

MyURLCache *URLCache = [[MyURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                                     diskCapacity:20 * 1024 * 1024
                                                         diskPath:[SDURLCache defaultCachePath]];
[NSURLCache setSharedURLCache:URLCache];

For each request need set cachePolicy to NSURLRequestReturnCacheDataElseLoad.

Or just use AFNetworking :)

- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 
              placeholderImage:(UIImage *)placeholderImage 
                       success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                       failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
Gralex
  • 3,854
  • 6
  • 24
  • 45
0

In all my apps I'm using this framework. Very simple to use

https://github.com/rs/SDWebImage

Code example

   [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]

];

Steaphann
  • 2,777
  • 6
  • 49
  • 106
0

Use This:

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
    NSString *savedImagePath = [NSString stringWithFormat:@"%@/%@",[paths objectAtIndex:0],[article.articleImage lastPathComponent]];
    UIImage *image = [UIImage imageNamed:savedImagePath];
    if(!image)
    {
       NSURL* url = [NSURL URLWithString:article.articleImage];
       NSURLRequest* request = [NSURLRequest requestWithURL:url];
       [NSURLConnection sendAsynchronousRequest:request
       queue:[NSOperationQueue mainQueue]
       completionHandler:^(NSURLResponse * response,
       NSData * data,
       NSError * error) 
       {
         if (!error)
         {
            [data writeToFile:savedImagePath atomically:NO]; 
             UIImage* image = [UIImage imageNamed:savedImagePath];
             MainImg.image = image;
             article.articleImg=image;
         }

    }];
  }
else
{
   MainImg.image = image;
   article.articleImg=image;
}
Prateek Prem
  • 1,544
  • 11
  • 13