ASIHTTPRequest是第三方包,使用前需要导入的包:MobileCoreServices、SystemConfiguration、CFNetwork、libz。
这里写的HttpDownload类可以实现用参数选择两种方式中一种来实现HTTP下载。并且通过callMethod函数实现回调。
下面是HttpDownload.h
#import <Foundation/Foundation.h> #import "ASIHTTPRequest.h" #define DOWNLOAD_SYSTEM 1 #define DOWNLOAD_ASIHTTPREQUEST 2 @interface HttpDownload : NSObject<ASIHTTPRequestDelegate,NSURLConnectionDataDelegate> { //回调的方法 SEL callMethod; //代理 id delegate; NSURLConnection *mConnection; NSInteger mType; //用于存放下载到的二进制数据 NSMutableData *mData; } @property (nonatomic,retain) NSMutableData *mData; -(void)downloadFromUrl:(NSString *)url delegate:(id)delegate selector:(SEL)selector type:(NSInteger)type; @end
下面是HttpDownload.m
m
#import "HttpDownload.h" @implementation HttpDownload @synthesize mData; //在初始化函数中为mData分配空间 -(id)init { if (self=[super init]) { mData=[[NSMutableData alloc] init]; } return self; } //dealloc时对mData进行内存回收 -(void)dealloc { self.mData=nil; [super dealloc]; } //参数一表示下载地址,参数二表示回调对象地址,参数3表示回调函数地址,参数四是下载类型 -(void)downloadFromUrl:(NSString *)url delegate:(id)newdelegate selector:(SEL)selector type:(NSInteger)type { delegate=newdelegate; callMethod=selector; //关于类型的宏定义 // #define DOWNLOAD_SYSTEM 1 // #define DOWNLOAD_ASIHTTPREQUEST 2 if (type==DOWNLOAD_ASIHTTPREQUEST) { ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]]; request.delegate=self; //启动异步下载 [request startAsynchronous]; //后面继续执行requestfinish或者requestFail方法 } else if(type==DOWNLOAD_SYSTEM){ if (mConnection) { [mConnection cancel]; [mConnection release]; } mConnection=[[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] delegate:self]; //后面执行connection:系列函数 } else{ NSLog(@"暂没实现"); } } //得到回应,即将开始开始接收数据时 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { //清空mData [mData setLength:0]; } //得到数据时 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //将数据存到mData [mData appendData:data]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { //检查代理是否可用以及是否实现方法callMethod if(delegate && [delegate respondsToSelector:callMethod]){ //调用对象delegate的方法callMethod传的参数为self [delegate performSelector:callMethod withObject:self]; //下面这个不能用,因为成员变量delegate是id类型的。 //[delegate callMethod:self]; } } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"系统下载失败"); } -(void)requestFinished:(ASIHTTPRequest *)request { [mData setLength:0]; [mData appendData:[request responseData]]; //检查代理是否可用以及是否实现方法callMethod if(delegate && [delegate respondsToSelector:callMethod]){ //调用对象delegate的方法callMethod传的参数为self [delegate performSelector:callMethod withObject:self]; //[delegate callMethod:self]; } } -(void)requestFailed:(ASIHTTPRequest *)request { NSLog(@"第三方下载失败"); } @end