NSURLSessionDownloadDelegate

- (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;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,712评论 2 7
  • NSURLSession概述1. NSURLSession session类型NSURLSession包括下面3种...
    瞎嘚嘚阅读 1,894评论 2 2
  • NSURLSession 使用步骤使用NSURLSession对象创建Task,然后执行Task -(void)g...
    BEYOND黄阅读 929评论 0 0
  • 使用NSURLConnection实现下载 1. 小文件下载 第一种方式(NSData) 第二种方式(NSURLC...
    搁浅的青蛙阅读 1,979评论 3 10
  • 在苹果彻底弃用NSURLConnection之后自己总结的一个网上的内容,加上自己写的小Demo,很多都是借鉴网络...
    付寒宇阅读 4,310评论 2 13