IOS中如何異步加載圖片(一)封裝自己的ImageDownLoad類

異步加載圖片是IOS軟件開發中經常用到的 下面便是一些具體的步驟與方法 希望可以幫到不懂的同學們 注意:這是在MRC環境下

自己封裝一個圖片下載的類 方便使用
在ImageDownload.h文件中寫入定義與聲明

@class ImageDownload;
//定義一個名叫SuccessBlock的block
typedef void(^SuccessBlock)(ImageDownload *imageDownload, UIImage *image);
//定義一個名叫ErrorBlock的block
typedef void(^ErrorBlock)(ImageDownload *imageDownload, NSError *error);


@interface ImageDownload : NSObject
// 定義block爲屬性的時候 一定要用copy 原因在於 block定義完後 本身是在棧區或者全局區,不在堆區。當定義成屬性的時候,需要copy一下 將其拷貝到堆區
@property (nonatomic, copy) SuccessBlock successBlock;
@property (nonatomic, copy) ErrorBlock errorBlock;

// 初始化方法,需要外界提供對應的網址
- (instancetype)initWithURLStr:(NSString *)urlStr;

// 便利構造器方法 方便外界使用
+ (ImageDownload *)imageDownloadWithURLStr:(NSString *)urlStr;
@end

在ImageDownload.m文件中寫下對應的實現方法

@interface ImageDownload ()<NSURLConnectionDataDelegate>

@property (nonatomic, retain)NSMutableData *receiveData;// 在延展裏面定義一個屬性用來存放下載的數據

@end


@implementation ImageDownload

- (void)dealloc
{
    [_receiveData release];
    // 對Block類型的變量進行釋放
    Block_release(_successBlock);
    Block_release(_errorBlock);
    [super dealloc];
}

-(NSMutableData *)receiveData
{
    if (_receiveData == nil) {
        self.receiveData = [NSMutableData dataWithCapacity:0];
    }
    return _receiveData;
}



// 初始化方法,需要外界提供對應的網址
- (instancetype)initWithURLStr:(NSString *)urlStr
{
    self = [super init];
    if (self) {
        NSURL *url = [NSURL URLWithString:urlStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];
        [[[NSURLConnection alloc]initWithRequest:request delegate:self] autorelease];
    }
    return self;
}

// 便利構造器方法 方便外界使用
+ (ImageDownload *)imageDownloadWithURLStr:(NSString *)urlStr
{
    ImageDownload *imageDownload = [[ImageDownload alloc]initWithURLStr:urlStr ];
    return [imageDownload autorelease];

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 拼接數據
    [self.receiveData appendData:data];
}


// block的調用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *image = [UIImage imageWithData:self.receiveData];
    self.successBlock(self,image);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    self.errorBlock(self,error);
}


@end

這樣 自己封裝的ImageDownload類就完成了 給外界提供了便利構造器的接口 可以使用
下面 就要開始我們的異步加載了 敬請期待。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章