//NSURLSessionDownloadTask
/* Creates a download task with the given request. */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;
/* Creates a download task to download the contents of the given URL. */
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;
/* Creates a download task with the resume data. If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;
// 下载任务支持 ` 断点续传 ` , 第三种方式通过之前已经下载的数据来创建下载任务。同样地可以通过 completionHandler 指定任务完成后的回调代码块。
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;
//首先在Main.storyboard添加按钮(button)和读取条(Progess View)
//在ViewController.m文件中定义全局变量
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIButton *bnt;
@property (nonatomic,strong)NSURLSessionDownloadTask *downloadTask;
@property (nonatomic ,strong)NSData *resumeData;
@property (nonatomic ,strong)NSURLSession *sessionDownload;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@",NSHomeDirectory());
}
//以(NSURLSession *)sharedSession方式获取NSURLSession类对象
-(void)downloadTask1{
//创建任务对象
NSURLSession *session =[NSURLSession shareSession];
//创建下载任务
//文件默认下载到tmp文件夹下。当下载完成后没有任何的处理会删掉,所以要在下载完成的时候把文件
//保存到别的文件夹中
NSURLSessionDownloadTask *downloadTask =[session downloadTaskWithURL:[NSURL URLWithString:@"
http://f.hiphotos.baidu.com/image/pic/item/e1fe9925bc315c60d916f9d58ab1cb134954770d.jpg
"]completionHandler"^(NSURL * _Nullale location,NSURLResponse * _Nullable response, NSError * _Nullable error){
//location.path
NSString *cachesPath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//建议使用的名字和服务器的名字一样
NSString * fileName = response.suggestedFilename;
NSString * filePath =[cachesPath stringByAppendingString:fileName];
NSFileManager * fileManger =[NSFileManager defaultManager];
[fileManger moveItemAtPath:location.path toPath:filepath error:nil];
}];
[downloadTask resume];
}
//以(NSURLSession *)
sessionWithConfiguration
方式获取NSURLSession类对象
</pre><p></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 13px; line-height: normal; font-family: Menlo;"></p><pre name="code" class="objc">(void)downloadTask2{
NSURLSessionConfiguration *configuration =[NSURLSessionConfiguration defaultSessionConfiguration];
self.sessionDownload =[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//创建下载任务
self .downloadTask =[self.sessionDownload downloadTaskWithURL:[NSURL URLWithString:@"http://b.zol-img.com.cn/desk/bizhi/image/7/2560x1600/145135666476.jpg"]];
//开启任务
[self.downloadTask resume];
}
#pragma mark --NSURLSessionDownloadDelegate--
//数据下载完成
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSString *cachesPath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *filePath = [cachesPath stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *fileManager =[NSFileManager defaultManager];
[fileManager moveItemAtPath:location.path toPath:filePath error:nil];
}
下载时读取条动作
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
self.progressView.progress =(CGFloat)totalBytesWritten /totalBytesExpectedToWrite;
NSLog(@"%f",(CGFloat)totalBytesWritten /totalBytesExpectedToWrite);
}
//通过按钮来通知任务下载和暂停
- (IBAction)butButton:(UIButton *)sender {
//[self downloadTask2];
if ([sender.titleLabel.text isEqualToString:@"下载"]) {
[sender setTitle:@"暂停" forState:UIControlStateNormal];
if (self.resumeData == nil) {
[self downloadTask2];
}else{
self.downloadTask= [self.sessionDownload downloadTaskWithResumeData:self.resumeData];
[self.downloadTask resume];
}
}else{
[sender setTitle:@"下载" forState:UIControlStateNormal];
[self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
self.resumeData =resumeData;
}];
self.downloadTask =nil;
}
}