(一)NSURLSession介绍
1.作用
- ① 通过URL下载资源到内存(NSData数据存储)
- ② 通过URL下载资源到磁盘中(沙盒中)
- ③ 给定URL上传资源到服务器
- ④ 可以在后台完成以上三个任务
- ⑤ 监控下载的进度
- ⑥ 断点续传
2.使用步骤
step①:创建url。创建session对象
- 方式一:session的单例对象(通用方式)
- 方式二:和delegate结合的创建方式(监控进度)
step②:创建task任务对象(默认是在子线程执行的)
- 数据任务:dataTask(下载的资源存储在内存中)
- NSURLSessionDataTask
- 下载任务:downloadTask(下载的资源存储磁盘中)
- NSURLSessionDownloadTask
- *上传任务:uploadTask
// --创建任务
(数据
任务
)
datatask
NSURLSessionDataTask
* datatask = [session
dataTaskWithRequest
:request
completionHandler
:^(
NSData
*
_Nullable
data,
NSURLResponse
*
_Nullable
response,
NSError
*
_Nullable
error) {}];
// --创建任务
(
下载任务
)
downloadtask
NSURLSessionDownloadTask
* downloadtask = [session
downloadTaskWithRequest
:request
completionHandler
:^(
NSURL
*
_Nullable
location,
NSURLResponse
*
_Nullable
response,
NSError
*
_Nullable
error) {
//参数 location:
沙盒中存储缓存的路径(
Libary/tmp
文件夹)
//注意:出了block方法体,存在沙盒中的缓存文件就会被清除
//
在主线中更新
UI
}];
step③:执行任务
- [task resume];
3.监听下载进度
①创建请求
NSURLRequest的对象
②创建 session(
NSURLSession)和 config(
NSURLSessionConfiguration)
- 将session绑定confige
- 设置代理对象,一般是self(当前控制器)
- 遵守代理协议 <NSURLSessionDownloadDelegate>(下载协议)
- 实现代理方法
//2. NSURLSession
和
config
配置对象绑定(设置代理)
NSURLSessionConfiguration * config = [ NSURLSessionConfiguration defaultSessionConfiguration ];
/**
* 参数一: config 配置对象
NSURLSessionConfiguration * config = [ NSURLSessionConfiguration defaultSessionConfiguration ];
/**
* 参数一: config 配置对象
*
参数二:设置代理
*
参数三:代理所在的队列,如果代理方法中是更新
UI
的操作,那么就应该写主队列
*/
*/
NSURLSession
* session = [
NSURLSession
sessionWithConfiguration
:config
delegate
:
self
delegateQueue
:[
NSOperationQueue
mainQueue
]];
③实现
<
NSURLSessionDownloadDelegate
>的代理方法。
//协议中选择实现的代理方法
//
下载数据时,会周期性调用的方法
/**
* 参数描述
*
* bytesWritten 每次服务器返回的数据的大小
* totalBytesWritten 已经写入的数据大小
* totalBytesExpectedToWrite 预计数据文件的总大小
*/
-( void )URLSession:( NSURLSession *)session downloadTask:( NSURLSessionDownloadTask *)downloadTask didWriteData:( int64_t )bytesWritten totalBytesWritten:( int64_t )totalBytesWritten totalBytesExpectedToWrite:( int64_t )totalBytesExpectedToWrite{
* 参数描述
*
* bytesWritten 每次服务器返回的数据的大小
* totalBytesWritten 已经写入的数据大小
* totalBytesExpectedToWrite 预计数据文件的总大小
*/
-( void )URLSession:( NSURLSession *)session downloadTask:( NSURLSessionDownloadTask *)downloadTask didWriteData:( int64_t )bytesWritten totalBytesWritten:( int64_t )totalBytesWritten totalBytesExpectedToWrite:( int64_t )totalBytesExpectedToWrite{
//
主线程执行,更新进度
self
.
progressView
.
progress
=
1.0
*totalBytesWritten / totalBytesExpectedToWrite;
//更新lable显示的百分比进度
self
.
progressLable
.
text
= [
NSString
stringWithFormat
:
@"%.2f%%”
,
self
.
progressView
.
progress
*
100];
}
//协议中必须实现的代理方法
//数据下载完毕后执行
-(
void
)URLSession:(
NSURLSession
*)session downloadTask:(
NSURLSessionDownloadTask
*)downloadTask didFinishDownloadingToURL:(
NSURL
*)location{
//
将文件存入别的文件夹(Library/cache)
NSString
* cache = [
NSSearchPathForDirectoriesInDomains
(
NSCachesDirectory
,
NSSystemDomainMask
,
YES
)
lastObject
];
NSString * pdffilepath = [cache stringByAppendingPathComponent : @"test.pdf" ];
NSString * pdffilepath = [cache stringByAppendingPathComponent : @"test.pdf" ];
NSError
* error =
nil
;
if (![[ NSFileManager defaultManager ] fileExistsAtPath :pdffilepath]) {
// 移动
[[ NSFileManager defaultManager ] moveItemAtURL :location toURL :[ NSURL fileURLWithPath :pdffilepath] error :&error];
if (!error) {
NSLog ( @" 移动成功 " );
}
}
if (![[ NSFileManager defaultManager ] fileExistsAtPath :pdffilepath]) {
// 移动
[[ NSFileManager defaultManager ] moveItemAtURL :location toURL :[ NSURL fileURLWithPath :pdffilepath] error :&error];
if (!error) {
NSLog ( @" 移动成功 " );
}
}
}
(二)NSURLResponse
1.核心属性
- expectedContentLength:预计文件总长度(byte)
- suggestedFilename: