NSURLSessionDownloadDelegate

2016-10-28  本文已影响100人  nothing_c

- (IBAction)downLoad:(id)sender {

if(_downloadTask) {

//重复点击按钮不会有重叠动作

return;

}else{

//路径

NSURL*url = [NSURL URLWithString:@"http://localhost:8080/UpLoad/myMusic.mp3"];

//对象

NSURLRequest *request = [NSURLRequest requestWithURL:url];

//创建会话

NSURLSession *session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];

//下载任务NSURLSessionDownloadTask

_downloadTask= [session downloadTaskWithRequest:request completionHandler:nil];

[_downloadTask resume];

}

}

#pragma mark -- NSURLSessionDownloadDelegate

//控制下载进度的

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {

NSLog(@"本次下载字节数:%lld已经下载字节数: %lld总共字节数:%lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);

//回主线程刷新UI

dispatch_async(dispatch_get_main_queue(), ^{

self.progressView.progress= (float)totalBytesWritten / totalBytesExpectedToWrite;

});

}

//下载完成调用存放在临时文件路径

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL*)location {

//location临时文件路径我们下载的文件出了该代理方法之后就会被移除掉,所以如果想保存文件,需要移动文件到其他路径

NSLog(@"location ----> %@",location);

//_downloadTask.response.suggestedFilename服务器中文件的名字

NSLog(@"++++%@",_downloadTask.response.suggestedFilename);

//移动文件到沙盒的Documents文件下

NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents"];

//拼接

NSString *file = [filePath stringByAppendingPathComponent:_downloadTask.response.suggestedFilename];

//移动

NSFileManager *manager = [NSFileManager defaultManager];

[managermoveItemAtPath:location.path toPath:file error:nil];

//置空可重复下载

_downloadTask = nil;

}

上一篇 下一篇

猜你喜欢

热点阅读