在下载大型文件过程中是可以取消下载的
- (IBAction)download:(UIButton *)sender {
// 状态取反
sender.selected = !sender.isSelected;
// 断点续传
// 断点下载if (sender.selected) { // 继续(开始)下载// 1.URLNSURL *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.conn cancel];self.conn = nil;
}
}
注意点:
(1)当再次需要下载的时候需要重新设计HTTP请求的头文件,使其在上一次下载结束的断点上继续下载—-断点续传
// 设置请求头
NSString *range = [NSString stringWithFormat:@”bytes=%lld-“, self.currentLength];
[request setValue:range forHTTPHeaderField:@”Range”];
(2)取消connection方法
[self.conn cancel];
self.conn = nil;