iOS中使用block进行网络请求回调
转自:http://www.tuicool.com/articles/JFRfmq
//
//HttpRequest.h
//UseBlockCallBack
//
//CreatedbyMichaelon2/13/14.
//Copyright(c)2014EIMS.Allrightsreserved.
//
#import<Foundation/Foundation.h>
typedefvoid(^FinishBlock)(NSString*dataString);
@interfaceHttpRequest:NSObject<NSURLConnectionDataDelegate>
@property(strong,nonatomic)NSMutableData*resultData;
@property(strong,nonatomic)FinishBlockfinishBlock;
+(void)postRequestWithURL:(NSString*)urlStr
paramters:(NSString*)paramters
finshedBlock:(FinishBlock)block;
@end
-----------------------------------------------------------------------
//
//HttpRequest.m
//UseBlockCallBack
//
//CreatedbyMichaelon2/13/14.
//Copyright(c)2014EIMS.Allrightsreserved.
//
#import"HttpRequest.h"
@implementationHttpRequest
+(void)postRequestWithURL:(NSString*)urlStr
paramters:(NSString*)paramters
finshedBlock:(FinishBlock)block
{
HttpRequest*httpRequest=[[HttpRequestalloc]init];
httpRequest.finishBlock=block;
NSURL*url=[NSURLURLWithString:urlStr];
NSMutableURLRequest*requset=[[NSMutableURLRequestalloc]initWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:30];
[requsetsetHTTPBody:[paramtersdataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection*connection=[[NSURLConnectionalloc]initWithRequest:requsetdelegate:httpRequest];
NSLog(connection?@"连接创建成功":@"连接创建失败");
}
/**
*接收到服务器回应的时回调
*/
-(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)response
{
NSHTTPURLResponse*httpResponse=(NSHTTPURLResponse*)response;
if(!self.resultData){
self.resultData=[[NSMutableDataalloc]init];
}else{
[self.resultDatasetLength:0];
}
if([responserespondsToSelector:@selector(allHeaderFields)]){
NSDictionary*dic=[httpResponseallHeaderFields];
NSLog(@"[network]allHeaderFields:%@",[dicdescription]);
}
}
/**
*接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次
*/
-(void)connection:(NSURLConnection*)connectiondidReceiveData:(NSData*)data
{
[self.resultDataappendData:data];
}
/**
*数据传完之后调用此方法
*/
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSString*resultStr=[[NSStringalloc]initWithData:self.resultData
encoding:NSUTF8StringEncoding];
if(self.finishBlock){
self.finishBlock(resultStr);
}
}
/**
*网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法
*/
-(void)connection:(NSURLConnection*)connectiondidFailWithError:(NSError*)error
{
NSLog(@"networkerror:%@",[errorlocalizedDescription]);
if(self.finishBlock){
self.finishBlock(nil);
}
}
@end
-----------------------------------------------------------------------
[HttpRequestpostRequestWithURL:@"http://www.baidu.com"
paramters:@""
finshedBlock:^(NSString*dataString){
NSLog(@"finishcallbackblock,result:%@",dataString);
}];