NSURLSessionDownloadTask下载图片

51 篇文章 0 订阅
#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 {

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值