断点下载

  1 #import "ViewController.h"
  2 
  3 @interface ViewController () <NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
  4 
  5 @property (weak, nonatomic) IBOutlet UIImageView *imgView;
  6 @property (weak, nonatomic) IBOutlet UIProgressView *progressView;
  7 
  8 
  9 /**  下载任务的属性  */
 10 @property (nonatomic, strong) NSURLSessionDownloadTask *task;
 11 
 12 /**  网络请求类  */
 13 @property (nonatomic, strong) NSURLSession *session;
 14 
 15 /**  发送请求类  */
 16 @property (nonatomic, strong) NSURLRequest *request;
 17 
 18 /**  保存已经下载的数据,供继续下载使用  */
 19 @property (nonatomic, strong) NSMutableData *data;
 20 
 21 
 22 @end
 23 
 24 @implementation ViewController
 25 
 26 - (void)viewDidLoad {
 27     [super viewDidLoad];
 28     
 29     // 设置progress的初始值
 30     self.progressView.progress = 0;
 31 }
 32 
 33 
 34 #pragma mark - 开始下载
 35 - (IBAction)start:(id)sender {
 36     
 37     // 下载的url
 38     NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/img/bdlogo.png"];
 39     
 40     // 初始化请求类
 41     self.request = [NSURLRequest requestWithURL:url];
 42     
 43     // 创建NSURLSession
 44     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
 45     self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
 46     
 47     // 下载请求任务
 48     self.task = [self.session downloadTaskWithRequest:self.request];
 49     
 50     // 开启
 51     [self.task resume];
 52 }
 53 
 54 
 55 #pragma mark - 暂停下载
 56 - (IBAction)pause:(id)sender {
 57     
 58     if (self.task) {
 59         
 60         __weak typeof(self)weakSelf = self;
 61         // 暂停并保存之前已经下载的内容
 62         [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
 63             
 64             weakSelf.data = [NSMutableData dataWithData:resumeData];
 65         }];
 66     }
 67     
 68     // 暂停任务
 69     [self.task suspend];
 70 }
 71 
 72 
 73 #pragma mark - 继续下载
 74 - (IBAction)continue:(id)sender {
 75     
 76     // 判断当前有没有任务,是发送请求,还是处理数据
 77     if (self.task != nil) {
 78         
 79         // 说明已经下载,这里要处理的就是数据
 80         self.task = [self.session downloadTaskWithResumeData:self.data];
 81     } else {
 82         
 83         // 此时没有下载任何内容,应该重新发送请求进行下载
 84         self.task = [self.session downloadTaskWithRequest:self.request];
 85     }
 86     
 87     // 启动
 88     [self.task resume];
 89 }
 90 
 91 
 92 #pragma mark - 代理方法
 93 // 下载完成的方法
 94 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
 95     
 96     NSFileManager *fileManager = [NSFileManager defaultManager];
 97     NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
 98     [fileManager moveItemAtPath:location.path toPath:path error:nil];
 99     self.imgView.image = [UIImage imageWithContentsOfFile:path];
100 }
101 
102 
103 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
104     
105     // 下载当前段的数据
106     NSLog(@"bytesWritten = %lld", bytesWritten);
107     
108     // 已经下载的总数据量
109     NSLog(@"totalBytesWritten = %lld", totalBytesWritten);
110     
111     // 总进度
112     NSLog(@"totalBytesExpectedToWrite = %lld", totalBytesExpectedToWrite);
113     
114     // 设置progress的进度值
115     self.progressView.progress = (CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;
116 }
117 
118 @end

 

转载于:https://www.cnblogs.com/zhizunbao/p/5543865.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OkHttp是一个开源的HTTP客户端库,用于在Android和Java应用程序中进行网络请求它提供了丰富的功能和易于使用的API,其中包括支持断点下载。 在OkHttp中实现断点下载可以通过以下步骤完成: 1. 创建OkHttpClient对象:首先,你需要创建一个OkHttpClient对象,它将用于发送HTTP请求。你可以使用默认的OkHttpClient实例,也可以根据需要进行自定义配置。 2. 创建Request对象:接下来,你需要创建一个Request对象,其中包含了你要下载的文件的URL。你可以使用Request.Builder来构建Request对象,并设置一些额外的参数,如请求头、请求方法等。 3. 设置Range头部:为了实现断点下载,你需要在请求头中设置Range头部。Range头部指定了服务器应该返回文件的哪个部分。你可以通过设置Range头部来指定下载的起始位置和结束位置。 4. 发送请求并处理响应:使用OkHttpClient发送请求,并获取响应。在响应中,你可以获取到文件的总大小和内容。 5. 保存文件:根据响应中的内容,你可以将文件保存到本地。如果是断点下载,你需要将新下载的内容追加到已有的文件中。 下面是一个简单的示例代码,演示了如何使用OkHttp进行断点下载: ```java OkHttpClient client = new OkHttpClient(); // 创建Request对象 Request request = new Request.Builder() .url("http://example.com/file.txt") .header("Range", "bytes=500-") // 设置Range头部,从第500字节开始下载 .build(); // 发送请求并获取响应 Response response = client.newCall(request).execute(); // 获取响应中的输入流 InputStream inputStream = response.body().byteStream(); // 创建文件输出流 FileOutputStream outputStream = new FileOutputStream("path/to/save/file.txt", true); // 追加模式 // 读取输入流并写入文件 byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } // 关闭流 outputStream.close(); inputStream.close(); ``` 请注意,上述代码仅为示例,实际使用时需要根据你的需求进行适当的修改和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值