NSURLSessionDownloadTask下载图片

#import "ViewController.h"

@interface ViewController ()
//显示进度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下载图片)