NSURLSessionDownloadTask 下载/断点下载

实现协议NSURLSessionDownloadDelegate的2个方法
此方法主要返回文件的字节数以及已下载的字节数

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;

储存的零时文件路径location

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location;

样式图,由于网速太快,手速跟不上,加载图片太快没来得及点击暂停下载以及就加载出来了,大家如果想实现可以把路径改为一个大一点的文件,这样就能看的很明显了。

这里写图片描述
这里写图片描述
代码实现

#import "ViewController.h"

@interface ViewController () <NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *loadImage;
@property (weak, nonatomic) IBOutlet UIProgressView *progress;
@property (weak, nonatomic) IBOutlet UILabel *loadPlan;
@property (weak, nonatomic) IBOutlet UIButton *loadTitle;

@property (nonatomic, strong) NSData *data;

@property (nonatomic, strong) NSURLSession *session;

@property (nonatomic, strong) NSURLSessionDownloadTask *task;

@property (nonatomic, assign) BOOL judgeDown;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
 *  下载的字节
 *
 *  @param session                   session
 *  @param downloadTask              taskdownload
 *  @param bytesWritten              每次下载的字节
 *  @param totalBytesWritten         已下载的字节
 *  @param totalBytesExpectedToWrite 总字节
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    //进度条计算
    CGFloat progress = (totalBytesWritten*1.0)/totalBytesExpectedToWrite;
    //异步添加到主队列下载
    dispatch_async(dispatch_get_main_queue(), ^{
        _progress.progress = progress;
        _loadPlan.text = [NSString stringWithFormat:@"开始下载:%d/100",(int)(progress*100)];
    }) ;
}
/**
 *  NSURLSessionDownloadDelegate委托协议
 *
 *  @param session      session
 *  @param downloadTask sessiontask
 *  @param location     储存的零时文件路径
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{

    NSFileManager *manager = [NSFileManager defaultManager];
    //获取document目录
    NSString *strDocument = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    //在原有路径上添加路径
    NSString *strURL = [strDocument stringByAppendingPathComponent:@"1250538257738.jpg"];
    //本地URL路径
    NSURL *url = [NSURL fileURLWithPath:strURL];

    if ([manager fileExistsAtPath:strURL]) {
        [manager removeItemAtPath:strURL error:nil];
    }
    //把tem文件移动指定的URL路径上
    if ([manager moveItemAtURL:location toURL:url error:nil]) {
        _data = [manager contentsAtPath:strURL];
        _loadImage.image = [UIImage imageWithData:_data];
    }


}
- (IBAction)onClick:(id)sender {
    NSString *strURL = @"http://img.pconline.com.cn/images/bbs4/20098/18/1250538257738.jpg";
    NSURL *url = [NSURL URLWithString:strURL];
    //创建config对象
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //创建session对象,并添加到主队列中
    _session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //下载路径
     _task = [_session downloadTaskWithURL:url];
    [_task resume];
}
- (IBAction)suspendLoad:(id)sender {
    if (_judgeDown) {
        NSLog(@"恢复下载");
        _loadTitle.titleLabel.text = @"暂停下载";
        if(!_data){
            NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/bbs4/20098/18/1250538257738.jpg"];
//            _request = [NSURLRequest requestWithURL:url];
//            _task = [_session downloadTaskWithRequest:_request];
            _task = [_session downloadTaskWithURL:url];
        }else{
            _task = [_session downloadTaskWithResumeData:_data];
        }
        [_task resume];
    }else{
        NSLog(@"暂停下载");
        _loadTitle.titleLabel.text = @"恢复下载";
        //取消下载并调用回调与恢复数据供以后使用
        [_task cancelByProducingResumeData:^(NSData *resumeData) {
            _data = resumeData;
        }];
        _task = nil;
        _judgeDown = YES;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值