29,028
社区成员
发帖
与我相关
我的任务
分享
- (void)start {
NSURL *url = [NSURL URLWithString:self.sourceUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
//实现暂停功能就是把每次下载的数据量纪录下来,然后通过这些来设置下次下载的请求头
NSString *value = [NSString stringWithFormat:@"bytes=%ld-%ld", self.startLocation+ self.currentLength, self.endLocation + 100];
[request setValue:value forHTTPHeaderField:@"Range"];
NSLog(@"请求头:%@",request.allHTTPHeaderFields);
self.connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
}
- (void)pause {
[self.connection cancel];
self.connection = nil;
}
- (void)end {
[self pause];
}
- (NSFileHandle *)fileHandle {
if (!_fileHandle) {
//调用这个方法,参数路径必须是实际存在的,否则返回一个空文件句柄
_fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.storePath];
}
return _fileHandle;
}
#pragma mark- NSURLConnection常用的代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"连接服务器成功");
NSLog(@"-----respose:%@",response);//这里可以看到服务器给你的所有反馈,挺有用
//每次连接到服务器一次(下载一次),就重新声明一个data来存储数据
self.tempData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"接收到数据");//调用多次,每次接受部分数据
[self.tempData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"这次下载所有的数据已经下载完毕");
[self.fileHandle writeData:self.tempData];
[self.fileHandle closeFile];
self.fileHandle = nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"%s",__FUNCTION__);
}
2016-03-12 14:02:52.924 DownloadRange[15134:5949962] 请求头:{
Range = "bytes=0-100";
}
2016-03-12 14:02:53.294 DownloadRange[15134:5949962] 连接服务器成功
2016-03-12 14:02:53.295 DownloadRange[15134:5949962] -----respose:<NSHTTPURLResponse: 0x7fafbac027e0> { URL: https://dn-nickey.qbox.me/124668.jpg } { status code: 206, headers {
"Accept-Ranges" = bytes;
"Access-Control-Allow-Origin" = "*";
"Access-Control-Expose-Headers" = "X-Log, X-Reqid";
"Access-Control-Max-Age" = 2592000;
"Cache-Control" = "public, max-age=31536000";
Connection = "keep-alive";
"Content-Disposition" = "inline; filename=\"124668.jpg\"";
"Content-Length" = 101;
"Content-Range" = "bytes 0-100/349812";
"Content-Transfer-Encoding" = binary;
"Content-Type" = "image/jpeg";
Date = "Sat, 12 Mar 2016 06:02:53 GMT";
Etag = "\"FrgKUK4hw_c9DDc6tq2bDghLrE7F\"";
"Last-Modified" = "Fri, 30 Oct 2015 03:36:19 GMT";
Server = "nginx/1.4.4";
"X-Log" = "mc.g;IO:2";
"X-Qiniu-Zone" = 0;
"X-Reqid" = jDAAAGJpXf6BAjsU;
"X-Via" = "1.1 jx129:88 (Cdn Cache Server V2.0), 1.1 xfzh13:1 (Cdn Cache Server V2.0)";
} }
2016-03-12 14:02:53.295 DownloadRange[15134:5949962] 接收到数据
2016-03-12 14:02:53.296 DownloadRange[15134:5949962] 这次下载所有的数据已经下载完毕