|
1
2
3
4
5
6
7
8
9
10
11
12
13 |
#import <Foundation/Foundation.h>//定义下载中的blocktypedef
void(^ProcessBlock)(NSURLResponse
*response,NSData
*data,NSError
*error);//定义下载完成的blocktypedef
void(^CompletionBlock)(NSURLResponse
*response,NSData
*data,NSError
*error);//接受网络连接协议@interface
CustomConnection : NSURLConnection<NSURLConnectionDataDelegate>+ (CustomConnection *)sendAsyRequest:(NSURLRequest
*)request andProcessBlock:(ProcessBlock)processblock andCompletionBlock:(CompletionBlock)completionblock;@end |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 |
#import "CustomConnection.h"@interface
CustomConnection ()@property
(nonatomic,strong)NSError
*error;@property
(nonatomic,strong)NSURLResponse
*response;@property
(nonatomic,strong)NSMutableData
*data;@property
(nonatomic,strong)CompletionBlock completionBlock;//在这里使用的是strong.引用计数加1(有内存管理)@property
(nonatomic,strong)ProcessBlock processBlock;@end@implementation
CustomConnection+ (CustomConnection *)sendAsyRequest:(NSURLRequest
*)request andProcessBlock:(ProcessBlock)processblock andCompletionBlock:(CompletionBlock)completionblock{ CustomConnection * connection = [[CustomConnection alloc]initWithRequest:request delegate:nil]; connection.completionBlock = completionblock; connection.processBlock = processblock; [connection start]; return
connection;}- (id)initWithRequest:(NSURLRequest
*)request delegate:(id)delegate{ //指定当前的网络连接工具类的代理对象是自己 self
= [super
initWithRequest:request delegate:self]; if
(self) { ; } return
self;}//收到网络连接响应的时候调用的方法- (void)connection:(NSURLConnection
*)connection didReceiveResponse:(NSURLResponse
*)response{ self.response = response; self.data = [[NSMutableData
alloc]init];}////收到网络链接发送信息时...- (void)connection:(NSURLConnection
*)connection didReceiveData:(NSData
*)data{ [self.data appendData:data]; self.processBlock (self.response,self.data,self.error);}//收到网络链接结束信息时...- (void)connectionDidFinishLoading:(NSURLConnection
*)connection{ self.completionBlock (self.response,self.data,self.error);}- (void)connection:(NSURLConnection
*)connection didFailWithError:(NSError
*)error{ self.error = error;}@end |
在使用的时候,
|
1
2
3
4
5
6
7
8
9
10
11
12 |
NSURL *url = [NSURL
URLWithString:@"http://www.taopic.com/uploads/allimg/110329/23-11032ZK01593.jpg"]; NSURLRequest
*request = [NSURLRequest
requestWithURL:url]; [CustomConnection sendAsyRequest:request andProcessBlock:^(NSURLResponse
*response, NSData
*data, NSError
*error) { UIImageView *imageV = [[UIImageView alloc]initWithImage:[UIImage imageWithData:data]]; imageV.frame = self.view.bounds; [self.view addSubview:imageV]; NSLog(@"下载中") ; } andCompletionBlock:^(NSURLResponse
*response, NSData
*data, NSError
*error) { NSLog(@"下载完成") ; }]; |
原文:http://www.cnblogs.com/yinyakun/p/3555795.html