netWorkQueue=[[ASINetworkQueue alloc]init];//创建队列
[netWorkQueue setShowAccurateProgress:YES];//高精度进度
[netWorkQueue go];//启动,启动后队列里的请求会自动执行
2。创建下载请求
- (IBAction)startDownload
{
//Documents路径
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//下载路径
downloadPath = [[path stringByAppendingPathComponent:@"book.zip"] retain];
//要支持断点续传,缓存路径是不能少的。
NSString *tempPath = [path stringByAppendingPathComponent:@"book.temp"];
//下载链接
NSURL *url = [NSURL URLWithString:@"http://cnread.net/cnread1/lszl/s/simaguang/zztj/zztj.zip"];
//创建请求
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
//设置代理,别忘了在头文件里添加ASIHTTPRequestDelegate协议
request.delegate = self;
//设置下载路径
[request setDownloadDestinationPath:downloadPath];
//设置缓存路径
[request setTemporaryFileDownloadPath:tempPath];
//设置支持断点续传
[request setAllowResumeForFileDownloads:YES];
//下载进度代理可以直接用UIProgressView对象,它会自动更新,如果你想做更多的处理
//就必须用我们自定义的类,只要我们的类里实现了setPorgress:方法
request.downloadProgressDelegate = self;
//将请求添加到之前创建的队列里,这时请求已经开始执行了
//队列会retain添加进去的请求
[queue addOperation:request];
}
由于我们没有设置代理方法,request会执行下列默认代理方法:
//请求开始
- (void)requestStarted:(ASIHTTPRequest *)request;
//请求收到响应的头部,主要包括文件大小信息,下面会用到
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders;
//请求将被重定向
- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL;
//请求完成
- (void)requestFinished:(ASIHTTPRequest *)request;
//请求失败
- (void)requestFailed:(ASIHTTPRequest *)request;
//请求已被重定向
- (void)requestRedirected:(ASIHTTPRequest *)request;
下面是我们对头部信息的处理
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
NSLog(@”%@”,responseHeaders);
if (fileLength == 0) {
fileLength = request.contentLength/1024.0/1024.0;
totalPro.text = [NSString stringWithFormat:@"%.2fM",fileLength];
}
}
这是打印的结果:
{
“Accept-Ranges” = bytes;
“Content-Length” = 4380152;
“Content-Type” = “application/x-zip-compressed”;
Date = “Fri, 25 Nov 2011 11:43:20 GMT”;
Etag = “\”16d81c5cba6c71:78c\”";
“Last-Modified” = “Sun, 03 Jun 2007 18:16:52 GMT”;
Server = “Microsoft-IIS/6.0″;
“X-Powered-By” = “ASP.NET”;
}
我们可以从中看到文件大小等一些请求信息,这时request自己也知道了文件大小,所以我们直接使用request的contentLength属性,放心,大小是一样的!
经过测试,缓存文件是在收到头部后创建的。