使用Block,线程封装网络请求

1.MyDownloader.h

1 #import <Foundation/Foundation.h>
2 
3 @interface MyDownloader : NSObject
4 
5 -(void)downloadWithUrlString:(NSString *)urlString finsh:(void (^)(NSData *))finishBlock fail:(void (^)(NSError *))failBlock;
6 //void (^finishBlock)(NSData *);
7 
8 @end
View Code

 

2.对应的MyDownloader.m

 1 #import "MyDownloader.h"
 2 
 3 @interface MyDownloader()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
 4 
 5 @end
 6 
 7 @implementation MyDownloader
 8 {
 9     //下载的数据
10     NSMutableData *_receiveData;
11     //下载
12     NSURLConnection *_conn;
13     
14     //下载结束调用的代码块
15     void (^_finishBlock)(NSData *);
16     void (^_failBlock)(NSError *);
17 }
18 
19 -(instancetype)init
20 {
21     self = [super init];
22     if (self) {
23         _receiveData = [NSMutableData data];
24     }
25     return self;
26 }
27 
28 -(void)downloadWithUrlString:(NSString *)urlString finsh:(void (^)(NSData *))finishBlock fail:(void (^)(NSError *))failBlock
29 {
30     if (_finishBlock != finishBlock) {
31         _finishBlock = nil;
32         _finishBlock = finishBlock;
33     }
34     
35     if (_failBlock != failBlock) {
36         _failBlock = nil;
37         _failBlock = failBlock;
38     }
39     
40     NSURL *url = [NSURL URLWithString:urlString];
41     NSURLRequest *request = [NSURLRequest requestWithURL:url];
42     
43     _conn = [NSURLConnection connectionWithRequest:request delegate:self];
44 }
45 
46 #pragma mark  ---NSURLConnectionDelegate----
47 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
48 {
49     [_receiveData setLength:0];
50 }
51 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
52 {
53     [_receiveData appendData:data];
54 }
55 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
56 {
57     _finishBlock(_receiveData);
58 }
59 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
60 {
61     _failBlock(error);
62 }
63 
64 @end
View Code

posted on 2015-09-07 15:06  Baymax01  阅读(180)  评论(0编辑  收藏  举报

导航