Monday, 9 April 2012

Get Cached image

//image cache
        MyImageView *imgView = [[MyImageView alloc] initWithFrame:CGRectMake(38, 15, 28, 27)];
        [imgView setBackgroundColor:[UIColor clearColor]];
        [imgView addImageFrom:imgURL];
        [cell addSubview:imgView];
-------------------------------------------------------------



#import <UIKit/UIKit.h>


@interface MyImageView : UIImageView
{

}

-(void) addImageFrom:(NSString*) URL;
-(void) fetchImage:(NSString*) str;
-(NSString*)  getUniquePath:(NSString*)  urlStr;
@end

-------------------------------------------------------------

//
//  MyImageView.m
//  iMixtapes
//
//  Created by Vipin Jain on 05/02/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MyImageView.h"
#define TMP NSTemporaryDirectory()

@implementation MyImageView


- (id)initWithFrame:(CGRect)frame {
   
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
    }
    return self;
}

-(void) addImageFrom:(NSString*) URL
{
    NSString *imgPath = [self getUniquePath:URL];
   
    if ([[NSFileManager defaultManager] fileExistsAtPath:imgPath])
    {
        NSData *data = [NSData dataWithContentsOfFile:imgPath];
        //if (self)
        [self setImage:[UIImage imageWithData:data]];
    }
    else
    {
        [NSThread detachNewThreadSelector:@selector(fetchImage:) toTarget:self withObject:URL];
    }
}

- (void)fetchImage:(NSString*) str
{
    NSURL *url = [NSURL URLWithString:str];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *tmpImage = [UIImage imageWithData:data];
   
    NSString *imgPath = [self getUniquePath:str];
    [data writeToFile:imgPath atomically:YES];
    //if (self)
    [self setImage:tmpImage];
}

- (NSString*)getUniquePath:(NSString*)  urlStr
{
   
    NSMutableString *tempImgUrlStr = [NSMutableString stringWithString:[urlStr substringFromIndex:7]];
    [tempImgUrlStr replaceOccurrencesOfString:@"/" withString:@"-" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempImgUrlStr length])];
   
    // Generate a unique path to a resource representing the image you want
    NSString *filename = [NSString stringWithFormat:@"%@",tempImgUrlStr] ;//[ImageURLString substringFromIndex:7];   // [[something unique, perhaps the image name]];
    NSString *uniquePath = [TMP stringByAppendingPathComponent: filename];
   
    return uniquePath;
}
                          
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code.
}
*/



@end

No comments:

Post a Comment