小牛一个希望大家多多关照。 上代码。
使用方法:造一个对象,调用
/**
* @brief 异步下载网络资源
*
* @param strURL URL连接(字符串形式)
* @param updater block,下载成功调用的方法
*/
- (void)asynchronousDownload:(NSString *)url
success:(Success)success
failure:(Failure)failure;
方法。
BLOCK 回调, 成功或失败。
#import <Foundation/Foundation.h>
@class Downloader;
typedef void(^Success)(Downloader *downloader);
typedef void(^Failure)(NSError *error);
@interface Downloader : NSObject <NSURLConnectionDataDelegate>
{
long double _length;
NSMutableData *_datas;
}
@property (nonatomic, assign) long double length;
@property (nonatomic, strong) NSMutableData *datas;
@property (nonatomic, copy) Success success;
@property (nonatomic, copy) Failure failure;
@property (nonatomic, strong) NSString *strURL;
/**
* @brief 异步下载网络资源
*
* @param strURL URL连接(字符串形式)
*/
- (void)asynchronousDownload:(NSString *)url;
/**
* @brief 异步下载网络资源
*
* @param strURL URL连接(字符串形式)
* @param updater block,下载成功调用的方法
*/
- (void)asynchronousDownload:(NSString *)url
success:(Success)success
failure:(Failure)failure;
@end
#import "Downloader.h"
@implementation Downloader
/**
* @brief 异步下载网络资源
*
* @param strURL URL连接(字符串形式)
*/
- (void)asynchronousDownload:(NSString *)strURL
{
NSLog(@"--->> Downloader 开始下载");
self.strURL = strURL;
NSURL *url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:100];
[NSURLConnection connectionWithRequest:request delegate:self];
}
/**
* @brief 异步下载网络资源
*
* @param strURL URL连接(字符串形式)
* @param success block,下载成功调用的方法
* @param failure block,下载失败调用的方法
*/
- (void)asynchronousDownload:(NSString *)url success:(Success)success failure:(Failure)failure
{
self.success = success;
self.failure = failure;
[self asynchronousDownload:url];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_length = response.expectedContentLength;
_datas = [NSMutableData dataWithCapacity:_length];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.datas appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"--->> Downloader 下载完成");
self.success(self);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"\n----------------download error----------------- \n%@", error);
self.failure(error);
}