{
NSURLConnection *_connection;
//文件句柄,缓存文件,必须存在
NSFileHandle *_handle;
long long _receiveSize;
long long _totalSize;
}
- (IBAction)StartAndPauseAction:(id)sender {
NSString *destionPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Cache/destion/aa.mov"];
NSLog(@"destionPath ---> %@",destionPath);
//判断文件是否存在
if(![[NSFileManager defaultManager] fileExistsAtPath:destionPath]) {
if(self.btn.tag == 1) {
//实现下载
NSString *tempPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Cache/temp/aa.mov"];
//获取文件的大小.属性等
NSDictionary *Dic = [[NSFileManager defaultManager] attributesOfItemAtPath:tempPath error:nil];
//获得已经下载的文件大小
_receiveSize= [[Dic objectForKey:NSFileSize] longLongValue];
NSString *urlStr =@"http://localhost:8080/UpLoad/XiaTianXieZouQu.rmvb";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
//key:Range表示返回数据的范围
//value:bytes=0-1000表示从0开始返回1000个字节
//value:bytes=1000-表示返回第1000个字节之后的所有数据
[request addValue:[NSString stringWithFormat:@"bytes=%lld-",_receiveSize] forHTTPHeaderField:@"Range"];
_connection = [NSURLConnection connectionWithRequest:request delegate:self];
self.btn.tag= 2;
[self.btn setTitle:@"正在下载" forState:UIControlStateNormal];
}else{
//暂停
[_connection cancel];
self.btn.tag=1;
[self.btn setTitle:@"继续下载" forState:UIControlStateNormal];
}
}else{
NSLog(@"文件已存在");
}
}
#pragma mark -- NSURLConnectionDataDelegate,NSURLConnectionDelegate
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
NSString *filePath =@"Cache/temp";
filePath = [filePath getExistsFilePathWithFileName:@"aa.mov"];
_handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse*)response;
_totalSize = HTTPResponse.expectedContentLength + _receiveSize;
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
_receiveSize =_receiveSize+ data.length;
self.ProgressView.progress= (float)_receiveSize/_totalSize;
NSLog(@"总的:%lld progress:%f",_totalSize,self.ProgressView.progress);
//从文件末尾写入
[_handle seekToFileOffset:[_handle seekToEndOfFile]];
[_handle writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
[_handle closeFile];
//搬移文件
//获取原路径
NSString *tempPath =@"Cache/temp";
tempPath = [tempPath getExistsFilePathWithFileName:@"aa.mov"];
//获取最终路径目标路径
NSString *destionPatn =@"Cache/destion";
destionPatn = [destionPatn getExistsFilePath];
destionPatn = [destionPatn stringByAppendingString:@"/aa.mov"];
NSLog(@"destionPatn ---> %@",destionPatn);
if([[NSFileManager defaultManager] moveItemAtPath:tempPath toPath:destionPatn error:nil]) {
NSLog(@"文件搬移成功");
}else{
NSLog(@"12");
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSErro r*)error {
NSLog(@"下载失败");
}