【iOS開發-網絡】使用NSURLSessionDownloadTask斷點下載

斷點下載也要實現代理方法

開始:創建task,開始任務
暫停:銷燬task,保存resumeData
恢復:重新創建task,傳遞resumeData


//開始下載
- (void) start {

   //創建NSURLSessionConfiguration對象
    NSURLSessionConfiguration *scf = [NSURLSessionConfiguration defaultSessionConfiguration];

    //創建session並且設置代理
    self.session = [NSURLSession sessionWithConfiguration:scf delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    //設置URL
    NSURL *url = [NSURL URLWithString:@"http://192.168.1.100:8080/TFServer/resources/videos/minion_01.mp4"];

//設置任務
    self.task = [self.session downloadTaskWithURL:url];

    //開始任務
    [self.task resume];
}

//回覆下載
- (void) resume {

//重新創建task
    self.task = [self.session downloadTaskWithResumeData:self.resumeData];

    //恢復下載
    [self.task resume];

    //把resumeData設置爲空
    self.resumeData = nil;
}

//暫停下載
- (void) pause {
    [self.task cancelByProducingResumeData:^(NSData *resumeData) {

        //保存resumeData
        self.resumeData = resumeData;
        self.task = nil;
    }];
}

代理方法

//下載完成調用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
    // location : 臨時文件的路徑(下載好的文件)

    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // response.suggestedFilename : 建議使用的文件名,一般跟服務器端的文件名一致

    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

    // 將臨時文件剪切或者複製Caches文件夾
    NSFileManager *mgr = [NSFileManager defaultManager];

    // AtPath : 剪切前的文件路徑
    // ToPath : 剪切後的文件路徑
    [mgr moveItemAtPath:location.path toPath:file error:nil];
}


//下載過程中調用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    double process = (double)totalBytesWritten / totalBytesExpectedToWrite;
    NSLog(@"-------%f", process);
}


//恢復下載調用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章