1. NSURLSession相關(guān)簡介
NSURLSession是iOS7的一個新特性,作為他的近親NSURLConnection已經(jīng)深感危機.iOS9的時候, 又被蘋果輕輕一推,稱霸武林的腳步往前邁了一大步...
1) .首先了解一下NSURLSession稱霸的資本:
NSURLSession 作為iOS7的一個新特性,它積極進化,除了保留NSURLConnection的基本組件NSURLRequest,NSURLCache,也增加NSURLSessionConfiguration和NSURLSessionTask(包含:
NSURLSessionDataTask: 普通的網(wǎng)絡(luò)數(shù)據(jù)請求
NSURLSessionUploadTask: 上傳
NSURLSessionDownloadTask: 下載
).
接下來主角就登場了--> NSURLSessionDownloadTask
它的凸顯優(yōu)勢:
a.不受蘋果后臺設(shè)置的時間的限制,可以在程序退到后臺后繼續(xù)session中未完成的task,直到全部完成退出后臺.
b.在服務(wù)器滿足蘋果API要求的情況下,讓斷點續(xù)傳擺脫bytes=%llu-
,更簡單易用(具體內(nèi)容接下來會提到)
c.在下載大的文件時做了相應(yīng)的優(yōu)化.之前為了避免下載的大的文件都存放在內(nèi)存中導(dǎo)致內(nèi)存激增,通常的優(yōu)化方案是存入沙盒 ,然后依次拼接.NSURLSessionDownloadTask
就是體貼到幫你解決這個問題(在下載過程中,打開沙盒文件,可以看到很多的.tmp臨時文件),而我們需要做的就是在下載完成的時候,在相應(yīng)的回調(diào)中把拼接完成的文件移動/拷貝到指定的文件夾下(使用AFNetWorking
則只需要指出存放的最終路徑)
2). 重要特性的介紹
** (1)NSURLSessionConfiguration配置**
創(chuàng)建NSURLSession的實例時,需要設(shè)置sessionWithConfiguration:
對創(chuàng)建的NSURLsession進行配置:
a). identifier 設(shè)置標識,設(shè)置后臺session configuration需要用到;
@property (nullable, readonly, copy) NSString *identifier;```
b). timeoutIntervalForRequest 超時限制 ;
c). allowsCellularAccess 是否允許蜂窩網(wǎng)絡(luò)下的數(shù)據(jù)請求
d). discretionary 允許后臺任務(wù)在性能最優(yōu)狀態(tài)下進行(當電量不足或者是蜂窩時將不進行,后臺任務(wù)建議設(shè)置該屬性)
```/* 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 創(chuàng)建的三種方法:**
> 1).//默認配置,硬盤存儲
```+ (NSURLSessionConfiguration*)defaultSessionConfiguration; ```
2).//臨時配置,內(nèi)存緩存
```+(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每創(chuàng)建一個task,相當于創(chuàng)建一個線程,在被調(diào)用之前,是掛起狀態(tài). 可以進行開始,暫停,取消等操作, 也可通過NSURLSessionTaskState查詢狀態(tài)為運行,掛起,取消或者完成.
NSURLSessionDownloadTask常用方法:
1)創(chuàng)建SessionDownLoadTask
a.創(chuàng)建一個新的任務(wù),沒有resumeData
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;
b.創(chuàng)建一個新的任務(wù),使用之前緩存的resumeData
```- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData ```
2)開始暫停取消相關(guān)操作
> ```- (void)resume; //開始下載(下載一個新的任務(wù)或者繼續(xù)下載(使用suspend進行暫停))```
```- (void)cancel; //取消(不保留之前緩存的數(shù)據(jù))```
```- (void)cancelByProducingResumeData:(void (^)(NSData * __nullable resumeData))completionHandler; //取消(保留之前緩存的數(shù)據(jù),方便下次緩存進行使用)```
```- (void)suspend; //暫停,相當于線程掛起,繼續(xù)下載時可以使用 resume 接著之前的繼續(xù)進行下載```
##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回調(diào)方法
- (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(@"*******下載任務(wù): %@ 進度: %lf", downloadTask, progress);
}];
//任務(wù)完成 前臺下載后臺下載均會執(zhí)行(返回下載完成之后需要存放的路徑)
[self.sessionManager setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) {
return [wealSelf createDirectoryForDownloadItemFromURL:location :downloadTask];
}];
//后臺下載結(jié)束才會執(zhí)行(執(zhí)行相應(yīng)的處理)
[self.sessionManager setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession *session) {
}];
}
####3)創(chuàng)建任務(wù)NSURLSessionDownloadTask
>```
- (void)createSessionTask{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
__weak MCDownSessionNode *weakSelf = self;
//創(chuàng)建任務(wù)
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相關(guān)簡介 -> 2). 重要特性的介紹-> (3) NSURLSessionDownloadTask -> 2)開始暫停取消相關(guān)操作
5)后臺下載delegate中的回調(diào)
-(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文件的配置(支持后臺下載)

##3.NSURLSession中遇到的坑
####1)斷點續(xù)傳這個梗
先回憶一下之前斷點續(xù)傳是怎么做的,在網(wǎng)上搜索也很自然的就能看到與下面一段相似的辦法,使用到 ```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;
}
現(xiàn)在,使用NSURLSessionDownloadTask,直接調(diào)用```- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;```方法就可實現(xiàn)斷點續(xù)傳,想想都覺得這么美,但是有兩個瓶頸:
a.從iOS7以及以上開始支持;
b.就是前面提到的服務(wù)器cdn要服從蘋果的設(shè)定條件,所以在你感覺方法都對,但獲取的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```