使用NSURLSessionDownloadTask下载文件的过程与前面差不多,需要注意的是文件下载文件之后会自动保存到一个临时目录,需要开发人员自己将此文件重新放到其他指定的目录中。
//
// ViewController.m
// NSURLSession
//
// Copyright © 2016年 asamu. All rights reserved.
// #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; [self downLoadFile];
} -(void)downLoadFile{
//1.创建 url
NSString *fileName = @"1.jpg";
NSString *urlStr = [NSString stringWithFormat:@"http://img3.douban.com/lpic/s4717862.jpg",fileName];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
//2.创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//创建会话
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(!error){
//location 是下载后的临时保存路径,需要将它移动到需要保存的位置
NSError *saveError = nil;
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
NSString *savePath = [cachePath stringByAppendingString:fileName];
NSLog(@"%@",savePath);
NSURL *url = [NSURL fileURLWithPath:savePath]; [[NSFileManager defaultManager]copyItemAtURL:location toURL:url error:&saveError];
if (!saveError) {
NSLog(@"save success");
}else{
NSLog(@"error is :%@",saveError.localizedDescription);
}
}else{
NSLog(@"error is :%@",error.localizedDescription);
}
}];
//执行任务
[downloadTask resume];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
} @end