NSURLSessionDownloadTask 后台下载

1. NSURLSession相关简介

NSURLSession是iOS7的一个新特性,作为他的近亲NSURLConnection已经深感危机.iOS9的时候, 又被苹果轻轻一推,称霸武林的脚步往前迈了一大步...

1) .首先了解一下NSURLSession称霸的资本:

NSURLSession 作为iOS7的一个新特性,它积极进化,除了保留NSURLConnection的基本组件NSURLRequest,NSURLCache,也增加NSURLSessionConfiguration和NSURLSessionTask(包含:
NSURLSessionDataTask: 普通的网络数据请求
NSURLSessionUploadTask: 上传
NSURLSessionDownloadTask: 下载
).

接下来主角就登场了--> NSURLSessionDownloadTask

它的凸显优势:

a.不受苹果后台设置的时间的限制,可以在程序退到后台后继续session中未完成的task,直到全部完成退出后台.
b.在服务器满足苹果API要求的情况下,让断点续传摆脱bytes=%llu-,更简单易用(具体内容接下来会提到)
c.在下载大的文件时做了相应的优化.之前为了避免下载的大的文件都存放在内存中导致内存激增,通常的优化方案是存入沙盒 ,然后依次拼接. NSURLSessionDownloadTask就是体贴到帮你解决这个问题(在下载过程中,打开沙盒文件,可以看到很多的.tmp临时文件),而我们需要做的就是在下载完成的时候,在相应的回调中把拼接完成的文件移动/拷贝到指定的文件夹下(使用AFNetWorking 则只需要指出存放的最终路径)

2). 重要特性的介绍

** (1)NSURLSessionConfiguration配置**
创建NSURLSession的实例时,需要设置sessionWithConfiguration:对创建的NSURLsession进行配置:

a). identifier 设置标识,设置后台session configuration需要用到;

@property (nullable, readonly, copy) NSString *identifier;```
b). timeoutIntervalForRequest 超时限制 ; 
c). allowsCellularAccess 是否允许蜂窝网络下的数据请求
d). discretionary  允许后台任务在性能最优状态下进行(当电量不足或者是蜂窝时将不进行,后台任务建议设置该属性)
```/* allows background tasks to be scheduled at the discretion of the system for optimal performance. */
@property (getter=isDiscretionary) BOOL discretionary NS_AVAILABLE(10_10, 7_0); ```
...


**(2) NSURLSessionConfiguration 创建的三种方法:**
>  1).//默认配置,硬盘存储
```+ (NSURLSessionConfiguration*)defaultSessionConfiguration;  ```
2).//临时配置,内存缓存
```+(NSURLSessionConfiguration*)ephemeralSessionConfiguration; ```  
3).//后台配置,iOS8.0以上
```+(NSURLSessionConfiguration*)backgroundSessionConfigurationWithIdentifier:(NSString*)identifier  NS_AVAILABLE(10_10,8_0); ```
//7_0,8_0 之间支持的后台配置
```+(NSURLSessionConfiguration*)backgroundSessionConfiguration:(NSString*)identifier NS_DEPRECATED(NSURLSESSION_AVAILABLE,10_10,7_0,8_0,"Please use backgroundSessionConfigurationWithIdentifier: instead");  ```


**(3)NSURLSessionDownloadTask**

NSURLSessionDownloadTask每创建一个task,相当于创建一个线程,在被调用之前,是挂起状态. 可以进行开始,暂停,取消等操作, 也可通过NSURLSessionTaskState查询状态为运行,挂起,取消或者完成.

NSURLSessionDownloadTask常用方法:
1)创建SessionDownLoadTask
a.创建一个新的任务,没有resumeData
  • (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;
    • (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;
b.创建一个新的任务,使用之前缓存的resumeData
  ```- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData ```

2)开始暂停取消相关操作
> ```- (void)resume; //开始下载(下载一个新的任务或者继续下载(使用suspend进行暂停))```
```- (void)cancel;  //取消(不保留之前缓存的数据)```
```- (void)cancelByProducingResumeData:(void (^)(NSData * __nullable resumeData))completionHandler;  //取消(保留之前缓存的数据,方便下次缓存进行使用)```
```- (void)suspend; //暂停,相当于线程挂起,继续下载时可以使用 resume 接着之前的继续进行下载```

##2. NSURLSessionDownloadTask的使用



#### 主要以第三方AFNetworking为例
####1)NSURLSessionConfiguration配置
>``` 
- (void)initSessionconfiguration
{
    NSURLSessionConfiguration *configuration ;
    if([[[[UIDevice currentDevice]systemVersion]substringToIndex:1] doubleValue]>=8){
        configuration= [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.xxxxxx.yyyyy"];
    }else{
        configuration= [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.xxxxxx.yyyyy"];
    }
    [configuration setAllowsCellularAccess:[self ifAllowsCellularAccess]];
    [configuration setNetworkServiceType:NSURLNetworkServiceTypeBackground];
    self.sessionManager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
}

2)AFURLSessionManager回调方法

 
  • (void)initAFURLSessionManager
    {
    __weak MCDownSessionManager *wealSelf = self;
    [self.sessionManager setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
    double progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
    NSLog(@"*******下载任务: %@ 进度: %lf", downloadTask, progress);
    }];
    //任务完成 前台下载后台下载均会执行(返回下载完成之后需要存放的路径)
    [self.sessionManager setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) {
    return [wealSelf createDirectoryForDownloadItemFromURL:location :downloadTask];
    }];
    //后台下载结束才会执行(执行相应的处理)
    [self.sessionManager setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession *session) {
    }];
    }
####3)创建任务NSURLSessionDownloadTask

>```
- (void)createSessionTask{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    __weak MCDownSessionNode *weakSelf = self;
    //创建任务
    self.sessionDownTask =
    [self.sessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        //好像没用上
        return [weakSelf createDirectoryForDownloadItemFromURL:targetPath];
    }completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error) {
            [weakSelf downLoadFailure];
        }else{
            [weakSelf downLoadComplete];
        }
    }];    
}

4)NSURLSessionDownloadTask的操作

参考 1. NSURLSession相关简介 -> 2). 重要特性的介绍-> (3) NSURLSessionDownloadTask -> 2)开始暂停取消相关操作

5)后台下载delegate中的回调

 

-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
{
//Check if all transfers are done, and update UI
//Then tell system background transfer over, so it can take new snapshot to show in App Switcher
// completionHandler(identifier);
//You can also pop up a local notification to remind the user
LSLog(@"[APPDelegate]________%@",identifier);
self.backgroundSessionCompletionHandler = completionHandler;
}

####6)plist文件的配置(支持后台下载)

![6952F2C4-AD44-44ED-B6F1-05EE4294A31C.png](http://upload-images.jianshu.io/upload_images/550807-22205ca98ec68cb7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


##3.NSURLSession中遇到的坑
####1)断点续传这个梗
先回忆一下之前断点续传是怎么做的,在网上搜索也很自然的就能看到与下面一段相似的办法,使用到 ```bytes=%llu-```:
NSString *tempPath = [self tempPath];//文件路径
        
        BOOL isResuming = NO;
        
        unsigned long long downloadedBytes = [self fileSizeForPath:tempPath];
        if (downloadedBytes > 0)
        {
            NSMutableURLRequest *mutableURLRequest = [urlRequest mutableCopy];
            NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];
            [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];
            self.request = mutableURLRequest;
            isResuming = YES;
        }
        
        if (!isResuming)
        {
            int fileDescriptor = open([tempPath UTF8String], O_CREAT | O_EXCL | O_RDWR, 0666);
            if (fileDescriptor > 0)
            {
                close(fileDescriptor);
            }
        }
        
        self.outputStream = [NSOutputStream outputStreamToFileAtPath:tempPath append:isResuming];
        if (!self.outputStream)
        {
            return nil;
        }
现在,使用NSURLSessionDownloadTask,直接调用```- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;```方法就可实现断点续传,想想都觉得这么美,但是有两个瓶颈:
a.从iOS7以及以上开始支持;
b.就是前面提到的服务器cdn要服从苹果的设定条件,所以在你感觉方法都对,但获取的resumeData是空的时候就可以考虑看一下API的Discussion(额,我就是在第三条上吃过亏的,两个cdn,一个能获得resumeData,一个不能):

A download can be resumed only if the following conditions are met:
The resource has not changed since you first requested it
The task is an HTTP or HTTPS GET request
The server provides either the ETag or Last-Modified header (or both) in its response
The server supports byte-range requests
The temporary file hasn’t been deleted by the system in response to disk space pressure```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值