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```

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容