ios 图片的网络下载和显示(可缓存)

思路是:已存在的图片则从本地读取,本地不存在的图片则从网上下载到本地

在这里下载图片使用的是ASIHTTPRequest,

asi-http-request的使用参考:http://blog.csdn.net/marujunyy/article/details/8474518


下面是用法和自己写的一个类的代码:

现在需要使用它的类的.h文件中添加delegate,如下:

#import <UIKit/UIKit.h>
#import "AsyncImageView.h"
@interface RelatedAppsUIView : UIView<AsyncImageDelegate>{
    
    __weak IBOutlet UIImageView *appImageView;
}

@end
然后在使用它的类的.m文件中添加代理的方法,如下:

#import "RelatedAppsUIView.h"

@implementation RelatedAppsUIView

-(void)awakeFromNib{
    AsyncImageView *asyncImageView=[[AsyncImageView alloc] init];
    //如果有多个图片,则添加tag
    
    asyncImageView.delegate=self;
    asyncImageView.tag=1001;
    [asyncImageView loadImageFromURL:[NSURL URLWithString:[@"http://csdnimg.cn/www/images/csdnindex_logo.gif" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
}

#pragma mark - AsyncImageDelegate

-(void)getImageSuccess:(UIImage *)image tag:(NSNumber *)tag
{
    NSLog(@"tag ->>%@",tag);
    appImageView.image=image;
}
-(void)getImageFail:(UIImage *)image tag:(NSNumber *)tag
{
    //TUDO 添加默认图片  错误返回
}
@end

下面是类:AsyncImageView的.h和.m文件的代码

//  AsyncImageView.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "ASIFormDataRequest.h"

@protocol AsyncImageDelegate <NSObject>

-(void)getImageSuccess:(UIImage *)image tag:(NSNumber *)tag;
-(void)getImageFail:(UIImage *)image tag:(NSNumber *)tag;

@end

@interface AsyncImageView : NSObject <ASIHTTPRequestDelegate>{
    NSURL *urls;
    id<AsyncImageDelegate> delegate;
    int tag;
}
@property (nonatomic,assign) int tag;
@property (nonatomic,retain)  id<AsyncImageDelegate> delegate;
- (void)loadImageFromURL:(NSURL*)url;
//-(NSString *)GetTempPath:(NSString*)filename;
-(BOOL)isExistsFile:(NSString *)filepath;
-(UIImage *)getImage:(NSString*)filename;
-(void)writeDataToFile:(NSString*)filename fileData:(NSData *)fileData;
-(NSString *) getCacheFilePath:(NSString *)filename;
@end

//  AsyncImageView.m

#import "AsyncImageView.h"

@implementation AsyncImageView
@synthesize delegate,tag;
- (void)dealloc {
    [delegate release];
    //    //NSLog(@"AsyncImageView delloc");
    [super dealloc];
}
- (void)loadImageFromURL:(NSURL*)url {
//    NSLog(@"--loadImageFromURL>>%@",url);
    if(url!=nil&&![url isEqual:@""]) {
        if ([self isExistsFile:[url description]]) {
            //返回数据 
            if ([delegate respondsToSelector:@selector(getImageSuccess:tag:)]) {
                [delegate performSelector:@selector(getImageSuccess:tag:) withObject:[self getImage:[url description]] withObject:[NSNumber numberWithInt:self.tag]];
            }
        }else{
            urls=url;
            [self retain];
            ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:urls] autorelease];
            [request setDelegate:self];
            [request startAsynchronous];
        }
    }
}
-(void)requestFailed:(ASIHTTPRequest *)request
{
    if ([delegate respondsToSelector:@selector(getImageFail:tag:)]) {
        [delegate performSelector:@selector(getImageFail:tag:) withObject:nil withObject:[NSNumber numberWithInt:self.tag]];
    }
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self release];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSData *responseData = [request responseData];
    UIImage *image=[UIImage imageWithData:responseData];
    if (image!=nil) {
        [self writeDataToFile:[urls description] fileData:responseData];
        if ([delegate respondsToSelector:@selector(getImageSuccess:tag:)]) {
            [delegate performSelector:@selector(getImageSuccess:tag:) withObject:image withObject:[NSNumber numberWithInt:self.tag]];
        }
    }else{
        if ([delegate respondsToSelector:@selector(getImageFail:tag:)]) {
            [delegate performSelector:@selector(getImageFail:tag:) withObject:image withObject:[NSNumber numberWithInt:self.tag]];
        }
    }
    [self release];
}
-(BOOL)isExistsFile:(NSString *)filepath
{
    NSFileManager *filemanage = [NSFileManager defaultManager];
    NSArray *array=[filepath componentsSeparatedByString:@"//"];
    NSArray *arrayName=[filepath componentsSeparatedByString:@"/"];
    NSString *file=[NSString stringWithFormat:@"%@/%@",[array lastObject],[arrayName lastObject]];
    return [filemanage fileExistsAtPath:[self getCacheFilePath:file]];
}
-(UIImage *)getImage:(NSString*)filename
{
    NSArray *array=[filename componentsSeparatedByString:@"//"];
    NSArray *arrayName=[filename componentsSeparatedByString:@"/"];
    NSString *file=[NSString stringWithFormat:@"%@/%@",[array lastObject],[arrayName lastObject]];
    UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfFile:[self getCacheFilePath:file]]];
    return image;
}
-(NSString *) getCacheFilePath:(NSString *)filename
{
	NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
	NSString *path=[paths objectAtIndex:0];
	NSString *filePath=[path stringByAppendingPathComponent:filename];
	return filePath;
}
-(void)writeDataToFile:(NSString*)filename fileData:(NSData *)fileData
{
    NSArray *array=[filename componentsSeparatedByString:@"//"];
    [[NSFileManager defaultManager] createDirectoryAtPath:[self getCacheFilePath:[array lastObject]] withIntermediateDirectories:YES attributes:nil error:nil];
    NSArray *arrayName=[filename componentsSeparatedByString:@"/"];
    NSString *file=[NSString stringWithFormat:@"%@/%@",[array lastObject],[arrayName lastObject]];
    [fileData writeToFile:[self getCacheFilePath:file] atomically:YES];
}
@end





你可能感兴趣的:(ios 图片的网络下载和显示(可缓存))