1.MyDownloader.h文件

1 #import <Foundation/Foundation.h> 2 3 //前置声明 4 @class MyDownloader; 5 //协议 6 @protocol MyDownloaderDelegate <NSObject> 7 8 //下载失败 9 - (void)downloader:(MyDownloader *)downloder failWithReeor:(NSError *)error; 10 11 //下载成功,并且下载结束 12 - (void)downloaderFinish:(MyDownloader *)downloader; 13 14 @end 15 16 17 //NSURLConnectionDelegate协议用来处理下载是成功还是失败 18 //NSURLConnectionDataDelegate 用来处理下载成功时的网络返回的数据 19 @interface MyDownloader : NSObject<NSURLConnectionDelegate,NSURLConnectionDataDelegate> 20 //下载的方法 21 -(void)downloadWithUrlString:(NSString *)urlString; 22 23 //代理属性: 24 //MRC:assign ARC:weak 25 /* 26 基本类型 代理属性 其它对象 27 MRC assign assign retain 28 ARC assign weak strong 29 */ 30 @property (nonatomic,weak)id<MyDownloaderDelegate>delegate; 31 32 //获取下载回来的数据(_receiveData) 33 //readonly 表示只会自动生成的getter方法 34 @property (nonatomic,strong)NSData *receiveData; 35 //类型 36 @property (nonatomic,assign)NSInteger type; 37 38 @end
2.MyDownloader.m文件

1 #import "MyDownloader.h" 2 @implementation MyDownloader 3 { 4 //下载对象 5 NSURLConnection *_conn; 6 //储存下来的数据 7 NSMutableData *_receiveData; 8 } 9 10 -(instancetype)init 11 { 12 self = [super init]; 13 if (self) { 14 //初始化下载数据的对象 15 _receiveData = [NSMutableData data]; 16 } 17 return self; 18 } 19 20 -(void)downloadWithUrlString:(NSString *)urlString 21 { 22 //1.创建NSURL类型的对象 23 NSURL *url = [NSURL URLWithString:urlString]; 24 25 //2.创建NSURLRequest类型的对象 26 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 27 28 //3.创建NSURLConnection类型的对象 29 _conn = [NSURLConnection connectionWithRequest:request delegate:self]; 30 } 31 32 #pragma mark - NSURLConnection代理 33 //下载成功 34 //准备接受数据 35 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 36 { 37 [_receiveData setLength:0]; 38 } 39 //接受下载回来的数据 40 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 41 { 42 [_receiveData appendData:data]; 43 } 44 //下载完成 45 //程序会自动切换到主线程 46 -(void)connectionDidFinishLoading:(NSURLConnection *)connection 47 { 48 if (self.delegate) { 49 [self.delegate downloaderFinish:self]; 50 } 51 } 52 //下载失败 53 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 54 { 55 if (self.delegate) { 56 [self.delegate downloader:self failWithReeor:error]; 57 } 58 } 59 60 @end