前言
- 無論是NSURLConnection還是NSURLSession要實(shí)現(xiàn)斷點(diǎn)續(xù)傳,原理都差不多:記錄下載位置,下次開始下載的時(shí)候帶著該位置請(qǐng)求網(wǎng)絡(luò)即可.
- 下面只介紹下NSURLSession的斷點(diǎn)續(xù)傳,文章末尾的demo里NSURLConnection和NSURLSession都實(shí)現(xiàn)了斷點(diǎn)續(xù)傳,大家可以自取.
封裝了一個(gè)類,演示下實(shí)現(xiàn)過程,上代碼
//
// YYSessionVC.m
// 文件下載(可斷點(diǎn)續(xù)傳)
//
// Created by yyMae on 16/1/21.
// Copyright (c) 2016年 yyMae. All rights reserved.
//
#import "YYSessionVC.h"
@interface YYSessionVC ()<NSURLSessionDownloadDelegate>
//顯示下載進(jìn)度
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UILabel *progressL;
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;//下載任務(wù)
@property (nonatomic, strong) NSData *resumeData;//記錄下載位置
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) UIButton *button;
@end
@implementation YYSessionVC
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"NSURLSession";
[self addView];
//NSLog(@"%@",NSHomeDirectory());
}
- (void)addView{
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(0, 0, 200, 20);
button.center = CGPointMake(self.view.frame.size.width * 0.5, 250);
[button setTitle:@"download" forState:UIControlStateNormal];
[button addTarget:self action:@selector(download1:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
self.button = button;
UIProgressView *progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
progressView.center = CGPointMake(self.view.frame.size.width * 0.5, 150);
[self.view addSubview:progressView];
self.progressView = progressView;
UILabel *progressL = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
progressL.center = CGPointMake(progressView.center.x, 190);
progressL.text = @"下載進(jìn)度:0.000000";
[self.view addSubview:progressL];
self.progressL = progressL;
}
/**
* session懶加載
*
* @return session
*/
-(NSURLSession *)session{
if (_session == nil) {
//??????
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
//從0開始下載
- (void)start{
//conerstone下載地址
NSURL* url = [NSURL URLWithString:@"http://att4.weiphone.net/temp16/201405/06/7/Cornerstone_v2.7.10.dmg"];
//創(chuàng)建下載任務(wù)
self.downloadTask = [self.session downloadTaskWithURL:url];
//開始任務(wù)
[self.downloadTask resume];
}
//繼續(xù)下載
- (void)resume{
//傳入上次暫停返回的數(shù)據(jù)
self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
//開始任務(wù)
[self.downloadTask resume];
self.resumeData = nil;
}
//暫停下載
- (void)pause{
__weak typeof(self) selfVC = self;
[self.downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
selfVC.resumeData = resumeData;
selfVC.downloadTask = nil;
}];
}
- (void)download1:(UIButton *)sender{
sender.selected = !sender.isSelected;
if (nil == self.downloadTask) {
if (self.resumeData) {//繼續(xù)下載
[self.button setTitle:@"暫停" forState:UIControlStateNormal];
[self resume];
}else{//開始下載
[self.button setTitle:@"暫停" forState:UIControlStateNormal];
[self start];
}
}else{//暫停下載
[self.button setTitle:@"繼續(xù)" forState:UIControlStateNormal];
[self pause];
}
}
#pragma mark -- NSURLSessionDownloadDelegate
/**
* 下載完成調(diào)用
*
* @param session
* @param downloadTask
* @param location 文件臨時(shí)地址
*/
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
//獲取文件路徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
//剪切文件到路徑
NSFileManager *fm = [NSFileManager defaultManager];
[fm moveItemAtPath:location.path toPath:filePath error:nil];
//提示下載完成
[[[UIAlertView alloc]initWithTitle:@"下載完成" message:downloadTask.response.suggestedFilename delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil] show];
}
/**
* 每次寫入沙盒完畢調(diào)用
*
* @param session
* @param downloadTask
* @param bytesWritten 本次寫入大小
* @param totalBytesWritten 已經(jīng)寫入大小
* @param totalBytesExpectedToWrite 文件總大小
*/
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
//下載進(jìn)度
self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
NSString *str = [NSString stringWithFormat:@"下載進(jìn)度:%f",(double)totalBytesWritten / totalBytesExpectedToWrite];
self.progressL.text = str;
}
/**
* 恢復(fù)下載時(shí)調(diào)用
*
* @param session
* @param downloadTask
* @param fileOffset
* @param expectedTotalBytes
*/
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
}
@end
demo下載地址
https://github.com/yyMae/download