一,头文件
#import <Foundation/Foundation.h>
//定义下载中block类型
typedef void(^ProcessBlock) (NSURLResponse *response,NSData *data,NSError *error);
//定义下载完成block类型
typedef void(^CompletionBlock) (NSURLResponse *response,NSData *data,NSError *error);
@interface BlockURLConnection : NSURLConnection<NSURLConnectionDataDelegate>
+(BlockURLConnection *)sendAsynchronousRequest:(NSURLRequest *)request ProcessBlock:(ProcessBlock)process CompletionBlock:(CompletionBlock)completion;
@end
二,实现部分
#import "BlockURLConnection.h"
@interface BlockURLConnection()
@property (nonatomic,strong ) NSError *error;
@property (nonatomic,strong ) NSMutableData *data;
@property (nonatomic,strong ) NSURLResponse *response;
@property (nonatomic,strong ) ProcessBlock process;
@property (nonatomic,strong ) CompletionBlock completion;
@end
@implementation BlockURLConnection
+(BlockURLConnection *)sendAsynchronousRequest:(NSURLRequest *)request ProcessBlock:(ProcessBlock)process CompletionBlock:(CompletionBlock)completion
{
BlockURLConnection *connection=[[BlockURLConnection alloc]initWithRequest:request delegate:self];
connection.process=process;
connection.completion=completion;
return connection;
}
-(id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate
{
//指定网络链接的代理是自己
if (self=[super initWithRequest:request delegate:self]) {
;
}
return self;
}
//收到链接错误信息
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.error=error;
}
//收到网络响应信息
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.response=response;
self.data=[NSMutableData data];
}
//收到网络消息
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.data appendData:data];
self.process(self.response,data,self.error);
}
//完成接受网络消息
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.completion(self.response,self.data,self.error);
}
@end