iOS 图片下载封装 ImageDownloader

#import 
#import 
@interface ImageDownload : NSObject
//下载图片并用Block返回
-(void)downLoadImageUrl:(NSURL *)imageUrl recevieImage:(void(^)(UIImage *image))imageBlock;
//单例
+(instancetype)defaultDownload;
@end

图片下载是iOS开发中的常用功能,但系统并没有提供致辞下载的类;

为了方便后续使用,可以将图片下载封装到一个类里面(imageDownloader)

ImageDownloader允许用户外界指定URL,提供ing开始下载和取消下载功能,并用delegate 或者block将图片传递给外接;


使用block传值 block传值介绍 :http://blog.csdn.net/zero_jones/article/details/49072103

#import "ImageDownload.h"

@interface ImageDownload ()
@property(nonatomic,strong) NSMutableArray *imageNameArray;
@end

@implementation ImageDownload
//初始化
-(instancetype)init{
    self = [super init];
    if (self) {
        self.imageNameArray = [[NSMutableArray alloc]init];
    }
    return self;
}
//单例
//声明全局变量

 static ImageDownload *download = nil;

 +(instancetype)defaultDownload
{
    @synchronized(self){
    if (download == nil) {
        download = [[ImageDownload alloc]init];
    }}
    return download;
}

//下载图片并用Block返回
-(void)downLoadImageUrl:(NSURL *)imageUrl recevieImage:(void(^)(UIImage *image))imageBlock{
    //首先判断imageUrl 和imageBlock 正确则继续执行
    if (!imageUrl || !imageBlock) {
        return;
    }
    //获取文本路径
    NSString *filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *fileName = [filePath stringByAppendingPathComponent:@"abcd"];
    NSLog(@"fileName= %@",fileName);
    //判断是否下载过
    if ([self.imageNameArray containsObject:imageUrl.path]) {
        //下载过的图片直接取
        NSData *data = [[NSData alloc]initWithContentsOfFile:fileName];
        UIImage *image = [[UIImage alloc]initWithData:data];
        //返回图片
        imageBlock(image);
        NSLog(@"在本地获取");
    }else{
    

        NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError || !data) {
                NSLog(@"error");
                return ;
            }
            UIImage *image = [[UIImage alloc]initWithData:data];
            //返回图片
            imageBlock(image);
            //把data存到本地
            [data writeToFile:fileName atomically:YES];
            //把下载过的图片加到数组
            [self.imageNameArray addObject:imageUrl.path];
            NSLog(@"下载图片%@,并存储",image);
            
        }];

    }
    
}

@end

你可能感兴趣的:(Objective-C)