断点下载文件(断点续传)

在实现之前,需要写一个滚动条表示下载进度,一个下载或者暂停的按钮。
// NSURLConnectionDataDelegate代理方法
// 请求失败时调用(请求超时、网络异常)
- (void)connection:(NSURLConnection )connection didFailWithError:(NSError )error{
NSLog(@”didFailWithError”);
}
// 1.接收到服务器的响应就会调用
// @param response 响应
- (void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse )response{
if (self.currentLength) return; //有此判断的作用是因为当下载完事之后,要是重启避免再次下载
// 文件路径
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepath = [caches stringByAppendingPathComponent:@”videos.zip”];
// 创建一个空的文件 到 沙盒中
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr createFileAtPath:filepath contents:nil attributes:nil];
// 创建一个用来写数据的文件句柄
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];
// 获得文件的总大小
self.totalLength = response.expectedContentLength;
}
// 2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)
// 这次返回的数据
- (void)connection:(NSURLConnection )connection didReceiveData:(NSData )data{
// 移动到文件的最后面
[self.writeHandle seekToEndOfFile];
// 将数据写入沙盒
[self.writeHandle writeData:data]; //以上两句目的是为了控制内存,不让内存里面文件太大而崩溃
// 累计文件的长度
self.currentLength += data.length;
self.circleView.progress = (double)self.currentLength/ self.totalLength;
}
// 3.加载完毕后调用(服务器的数据已经完全返回后)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
self.currentLength = 0;
self.totalLength = 0;
// 关闭文件
[self.writeHandle closeFile];
self.writeHandle = nil;
}
//以下是写的一个开始或者暂停下载的按钮
- (IBAction)download:(UIButton *)sender {
// 状态取反
sender.selected = !sender.isSelected;
if (sender.selected) { // 继续(开始)下载
// 1.URL
NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/videos.zip“];
// 2.请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 设置请求头
NSString *range = [NSString stringWithFormat:@”bytes=%lld-“, self.currentLength];
[request setValue:range forHTTPHeaderField:@”Range”];
// 3.下载(创建完conn对象后,会自动发起一个异步请求)
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
} else { // 暂停时,自然不会走代理方法,self.currentLength就不会变化,进度条就不会改变,从而达到暂停的效果
[self.conn cancel];
self.conn = nil;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值