#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
//显示进度label
@property (weak, nonatomic) IBOutlet UILabel *progressPercentLabel;
//进度视图
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
//下载任务
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
//session会话
@property (nonatomic, strong) NSURLSession *session;
//记录点击暂停按钮时返回的数据点(附加信息)
@property (nonatomic, strong) NSData *resumeData;
@end
@implementation ViewController
- (IBAction)startDownloadImage:(id)sender {
//0.NSURL
NSURL *url = [NSURL URLWithString:@"http://images.apple.com/v/iphone-5s/gallery/a/images/download/photo_4.jpg"];
//1.session
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//2.task
self.downloadTask = [self.session downloadTaskWithURL:url];
//3.resume(执行)
[self.downloadTask resume];
}
//暂停正在下载的任务
- (IBAction)cancelImage:(id)sender {
[self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
//resumeData:在点击暂停按钮的时候的已经下载的数据(Range)
if (!resumeData) {
return;
}
self.resumeData = resumeData;
}];
}
//恢复下载任务(重新发送请求)
- (IBAction)resumeImage:(id)sender {
if (self.resumeData) {
self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
//重新执行下载任务
[self.downloadTask resume];
}
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
//更新进度视图值
self.progressView.progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
//更新label文本(目前下载总大小/总大小)
self.progressPercentLabel.text = [NSString stringWithFormat:@"%lld/%lld",totalBytesWritten, totalBytesExpectedToWrite];
}
//必须实现的方法!!!
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
}
NSURLSessionDownloadTask下载图片
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Python应用现在如火如荼,应用范围很广。因其效率高开发迅速的优势,快速进入编程语言排行榜前几名。本系列文章致力...
- 为按钮设置网络图片, 可以使用SDWebImage第三方库提供的UIButton+WebCache.h 分类 提供...
- 简粉下载是一款可以将简书上的文章保存为HTML和PDF文件的Windows软件,图文排版与简书保持一致,为文章(包...
- 一谈起中国电竞,大家最先想到的是什么? WCG?外国的。 魔兽,外国的。 星际,外国的。 CF,外国的。 DNF,...