NSURLSession實現斷點下載

NSURLSession實現斷點下載

@interface HMViewController () <NSURLSessionDownloadDelegate, NSURLSessionDataDelegate]]>

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
- (
IBAction)download:(UIButton *)sender;

@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@property (nonatomic, strong) NSURLSession *session;
@end

@implementation HMViewController

- (
NSURLSession *)session
{
   
if (!_session) {
       
// 獲得session
       
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
       
self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
   
return _session;
}

- (
IBAction)download:(UIButton *)sender {
   
// 按鈕狀態取反
    sender.
selected = !sender.isSelected;
   
   
if (self.task == nil) { // 開始(繼續)下載
       
if (self.resumeData) { // 恢復
            [
self resume];
        }
else { // 開始
            [
self start];
        }
    }
else { // 暫停
        [
self pause];
    }
}

/**
 * 
從零開始
 */

- (
void)start
{
   
// 1.創建一個下載任務
   
NSURL *url = [NSURL URLWithString:@"http://192.168.15.172:8080/MJServer/resources/videos/minion_01.mp4"];
   
self.task = [self.session downloadTaskWithURL:url];
   
   
// 2.開始任務
    [
self.task resume];
}

/**
 * 
恢復(繼續)
 */

- (
void)resume
{
   
// 傳入上次暫停下載返回的數據,就可以恢復下載
   
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
   
   
// 開始任務
    [
self.task resume];
   
   
// 清空
   
self.resumeData = nil;
}

/**
 * 
暫停
 */

- (
void)pause
{
   
__weak typeof(self) vc = self;
    [
self.task cancelByProducingResumeData:^(NSData *resumeData) {
       
//  resumeData : 包含了繼續下載的開始位置\下載的url
        vc.
resumeData = resumeData;
        vc.
task = nil;
    }];
}

#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(
NSURL *)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
{
   
NSLog(@"獲得下載進度--%@", [NSThread currentThread]);
   
// 獲得下載進度
   
self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
}

- (
void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(
int64_t)fileOffset
expectedTotalBytes:(
int64_t)expectedTotalBytes
{
   
}
發佈了82 篇原創文章 · 獲贊 13 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章