NSURLSessionDownloadTask 下載/斷點(diǎn)下載

實(shí)現(xiàn)協(xié)議NSURLSessionDownloadDelegate的2個方法
此方法主要返回文件的字節(jié)數(shù)以及已下載的字節(jié)數(shù)

- (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;

樣式圖,由于網(wǎng)速太快,手速跟不上,加載圖片太快沒來得及點(diǎn)擊暫停下載以及就加載出來了,大家如果想實(shí)現(xiàn)可以把路徑改為一個大一點(diǎn)的文件,這樣就能看的很明顯了。

屏幕快照 2016-04-14 下午1.33.37.png

屏幕快照 2016-04-14 下午1.32.49.png

代碼實(shí)現(xiàn)

#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.
}
/**
 *  下載的字節(jié)
 *
 *  @param session                   session
 *  @param downloadTask              taskdownload
 *  @param bytesWritten              每次下載的字節(jié)
 *  @param totalBytesWritten         已下載的字節(jié)
 *  @param totalBytesExpectedToWrite 總字節(jié)
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    //進(jìn)度條計算
    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委托協(xié)議
 *
 *  @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];
    //創(chuàng)建config對象
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //創(chuàng)建session對象,并添加到主隊列中
    _session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //下載路徑
     _task = [_session downloadTaskWithURL:url];
    [_task resume];
}
- (IBAction)suspendLoad:(id)sender {
    if (_judgeDown) {
        NSLog(@"恢復(fù)下載");
        _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 = @"恢復(fù)下載";
        //取消下載并調(diào)用回調(diào)與恢復(fù)數(shù)據(jù)供以后使用
        [_task cancelByProducingResumeData:^(NSData *resumeData) {
            _data = resumeData;
        }];
        _task = nil;
        _judgeDown = YES;
    }
}

@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,177評論 25 708
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,646評論 19 139
  • iOS開發(fā)系列--網(wǎng)絡(luò)開發(fā) 概覽 大部分應(yīng)用程序都或多或少會牽扯到網(wǎng)絡(luò)開發(fā),例如說新浪微博、微信等,這些應(yīng)用本身可...
    lichengjin閱讀 4,046評論 2 7
  • 小胖,實(shí)際就是小學(xué)時期的我兒子。 小學(xué)五年級,十一歲,他的體重已經(jīng)超過140斤了,個子還沒我這個不到一米六的矮冬瓜...
    那霞閱讀 637評論 0 2
  • 最近碩士畢業(yè)要論文查重,一直在忙這個事情,不斷地完善自己的文章,希望能平安順利地結(jié)束學(xué)生時代。 今天主要是跟大家分...
    指微寒閱讀 845評論 4 16

友情鏈接更多精彩內(nèi)容