#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@end
@implementation ViewController
#pragma mark - 开始
- (IBAction)start:(id)sender
{
//获取包含代理方法的网络会话:
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
//处理URL中含有中文的问题:stringByAddingPercentEncodingWithAllowedCharacters
NSString * urlString = [@"http://192.168.1.34/同步异步串行并发.mp4"stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//根据网络会话和URL创建网络下载任务:
self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:urlString]];
//开启下载任务:
[self.task resume];
}
#pragma mark - 暂停
- (IBAction)pause:(id)sender
{
//暂停就是把任务挂起:
[self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
// resumeData:已下载的数据:
//保存resumeData到self.resumeData:
self.resumeData = resumeData;
}];
}
#pragma mark - 继续
- (IBAction)resume:(id)sender
{
//根据保存的数据生成任务:
//继续执行网络下载任务 , 从已经下载的网络数据之后跟随下载:
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
//继续开启任务:
[self.task resume];
}
#pragma mark - <NSURLSessionDownloadDelegate>
//下载完成调用:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
//location tmp地址:
NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
cachePath = [cachePath stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachePath] error:nil];
}
//监听下载进度:
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
//bytesWritten 每次写入大小:
//totalBytesWritten 已经下载量 Written:
//totalBytesExpectedToWrite 总大小:
NSLog(@"%lf",totalBytesWritten * 1.0 / totalBytesExpectedToWrite);
}
//请求完成:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"结束请求");
}
@end
NSURLSession文件下载
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- NSURLSession使文件下载变得非常方便,只需要提供简单的配置,下面讲述使用NSURLSession实现文件...
- 导语 现在NSURLConnection在开发中会使用的越来越少,iOS9已经将NSURLConnection废弃...
- 一、 NSURLSession的基本使用 (1)使用步骤 (2)关于task (3)发送get请求 (4)发送ge...