NSURLSession實現斷點下載,nsurlsession
NSURLSession實現斷點下載
@interfaceHMViewController () <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
@implementationHMViewController
- (NSURLSession*)session
{
if (!_session) {
// 獲得session
NSURLSessionConfiguration *cfg = [NSURLSessionConfigurationdefaultSessionConfiguration];
self.session= [NSURLSessionsessionWithConfiguration:cfgdelegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
}
return _session;
}
- (IBAction)download:(UIButton*)sender {
// 按鈕狀態取反
sender.selected= !sender.isSelected;
if (self.task== nil) { // 開始(繼續)下載
if (self.resumeData) { // 恢複
[selfresume];
} else { // 開始
[selfstart];
}
} else { // 暫停
[selfpause];
}
}
/**
* 從零開始
*/
- (void)start
{
// 1.建立一個下載任務
NSURL *url = [NSURLURLWithString:@"http://192.168.15.172:8080/MJServer/resources/videos/minion_01.mp4"];
self.task= [self.sessiondownloadTaskWithURL:url];
// 2.開始任務
[self.taskresume];
}
/**
* 恢複(繼續)
*/
- (void)resume
{
// 傳入上次暫停下載返回的資料,就可以恢複下載
self.task= [self.sessiondownloadTaskWithResumeData:self.resumeData];
// 開始任務
[self.taskresume];
// 清空
self.resumeData= nil;
}
/**
* 暫停
*/
- (void)pause
{
__weak typeof(self) vc =self;
[self.taskcancelByProducingResumeData:^(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 = [cachesstringByAppendingPathComponent:downloadTask.response.suggestedFilename];
// 將臨時檔案剪下或者複製Caches檔案夾
NSFileManager *mgr = [NSFileManagerdefaultManager];
// AtPath : 剪下前的檔案路徑
// ToPath : 剪下後的檔案路徑
[mgr moveItemAtPath:location.pathtoPath:fileerror: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
{
}