目錄
1.斷點(diǎn)續(xù)傳概述;
2.斷點(diǎn)續(xù)傳原理;
3.簡單下載的實(shí)現(xiàn);
4.實(shí)現(xiàn)斷點(diǎn)續(xù)傳;
5.實(shí)現(xiàn)后臺下載
第一: 斷點(diǎn)續(xù)傳概述
斷點(diǎn)續(xù)傳就是從文件上次中斷
的地方開始重新下載或上傳數(shù)據(jù)
瓦盛,而不是從文件開頭律秃。
第二: 斷點(diǎn)續(xù)傳原理
要實(shí)現(xiàn)斷點(diǎn)續(xù)傳,服務(wù)器必須支持
拧烦。目前最常見的是兩種方式:FTP 和 HTTP
。下面來簡單介紹 HTTP 斷點(diǎn)續(xù)傳的原理:
斷點(diǎn)續(xù)傳
主要依賴于HTTP 頭部
定義的 Range 來完成
莉擒。具體 Range 的說明參見 RFC2616中 14.35.2 節(jié)酿炸。有了 Range,應(yīng)用可以通過 HTTP 請求獲取當(dāng)前下載資源的的位置
涨冀,進(jìn)而來恢復(fù)下載該資源
填硕。Range 的定義如圖 1 所示:
在上面的例子中的“Range: bytes=1208765-”表示請求資源開頭 1208765 字節(jié)之后的部分。
上面例子中的”Accept-Ranges: bytes”
表示服務(wù)器端接受請求資源的某一個范圍蝇裤,并允許對指定資源進(jìn)行字節(jié)類型訪問廷支。”Content-Range: bytes 1208765-20489997/20489998”
說明了返回提供了請求資源所在的原始實(shí)體內(nèi)的位置
,還給出了整個資源的長度
栓辜。這里需要注意的是 HTTP return code 是 206 而不是 200恋拍。
第三.簡單下載的實(shí)現(xiàn);
大家用慣了AFN
, 可能對于系統(tǒng)原生的不大熟悉, 為了直觀, 先回顧一些系統(tǒng)原生的東西----知其然知其所以然
以下代碼在當(dāng)前的currentSession
中創(chuàng)建一個網(wǎng)絡(luò)請求任務(wù)---可以取消的任務(wù)
, 并下載一個圖片展示出來;
效果圖為
#pragma mark 開始下載
- (IBAction)startDownload:(id)sender {
if (!self.cancelDownloadTask) {
self.imageView.image = nil;
NSString *imageURLStr = @"http://upload-images.jianshu.io/upload_images/326255-2834f592d7890aa6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240";
//創(chuàng)建網(wǎng)絡(luò)請求
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];
//將當(dāng)前session中創(chuàng)建下載取消的任務(wù)
self.cancelDownloadTask = [self.currentSession downloadTaskWithRequest:request];
//保證下載按鈕只點(diǎn)擊一次
[self setDownloadButtonsWithEnabled:NO];
//開始
[self.cancelDownloadTask resume];
}
}
下載的代理
創(chuàng)建了網(wǎng)絡(luò)請求, 之后主要的任務(wù)都在于下載的代理中做相應(yīng)的任務(wù).
#pragma mark 下載的代理
/**
* 每次寫入沙盒完畢調(diào)用
* 在這里面監(jiān)聽下載進(jìn)度,totalBytesWritten/totalBytesExpectedToWrite
*
* @param bytesWritten 這次寫入的大小
* @param totalBytesWritten 已經(jīng)寫入沙盒的大小
* @param totalBytesExpectedToWrite 文件總大小
*/
/* 執(zhí)行下載任務(wù)時(shí)有數(shù)據(jù)寫入 */
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
// 計(jì)算當(dāng)前下載進(jìn)度并更新視圖
float downloadProgress = totalBytesWritten / (float)totalBytesExpectedToWrite;
NSLog(@"----%@", [NSThread currentThread]);
WeakSelf;
dispatch_async(dispatch_get_main_queue(), ^{
/* 根據(jù)下載進(jìn)度更新視圖 */
weakSelf.progressView.progress = downloadProgress;
});
}
/* 從fileOffset位移處恢復(fù)下載任務(wù) */
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
NSLog(@"NSURLSessionDownloadDelegate: Resume download at %lld", fileOffset);
}
/* 完成下載任務(wù)藕甩,無論下載成功還是失敗都調(diào)用該方法 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"=====%@", [NSThread currentThread]);
//恢復(fù)按鈕的點(diǎn)擊效果
[self setDownloadButtonsWithEnabled:YES];
if (error) {
NSLog(@"下載失斒└摇:%@", error);
self.progressView.progress = 0.0;
self.imageView.image = nil;
}
}
其中, 我們操作最多的該是下邊這個代理
/* 完成下載任務(wù),只有下載成功才調(diào)用該方法 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSLog(@"NSURLSessionDownloadDelegate: Finish downloading");
NSLog(@"----%@", [NSThread currentThread]);
// 1.將下載成功后的文件<在tmp目錄下>移動到目標(biāo)路徑
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileArray = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *destinationPath = [fileArray.firstObject URLByAppendingPathComponent:[location lastPathComponent]];
NSLog(@"----路徑--%@/n---%@", destinationPath.path, location);
if ([fileManager fileExistsAtPath:[destinationPath path] isDirectory:NULL]) {
[fileManager removeItemAtURL:destinationPath error:NULL];
}
//在此有個下載文件后綴的問題
//2將下載默認(rèn)的路徑移植到指定的路徑
NSError *error = nil;
if ([fileManager moveItemAtURL:location toURL:destinationPath error:&error]) {
self.progressView.progress = 1.0;
//刷新視圖狭莱,顯示下載后的圖片
UIImage *image = [UIImage imageWithContentsOfFile:[destinationPath path]];
WeakSelf;
//回主線程
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.imageView.image = image;
});
}
// 3.取消已經(jīng)完成的下載任務(wù)
if (downloadTask == self.cancelDownloadTask) {
self.cancelDownloadTask = nil;
}else if (downloadTask == self.resumableDownloadTask) {
self.resumableDownloadTask = nil;
self.resumableData = nil;
}else if (session == self.backgroundSession) {
self.backDownloadTask = nil;
AppDelegate *appDelegate = [AppDelegate sharedDelegate];
if (appDelegate.backgroundURLSessionCompletionHandler) {
// 執(zhí)行回調(diào)代碼塊
void (^handler)() = appDelegate.backgroundURLSessionCompletionHandler;
appDelegate.backgroundURLSessionCompletionHandler = nil;
handler();
}
}
}
**請思考一下: 為何要回主線程中更新視圖? **
知道了斷點(diǎn)續(xù)傳的大致原理以及下載的常用方法, 接下來就先實(shí)現(xiàn)斷點(diǎn)續(xù)傳
第四.實(shí)現(xiàn)斷點(diǎn)續(xù)傳---下載了較大的文件
蘋果在 iOS7 開始僵娃,推出了一個新的類 NSURLSession, 它具備了 NSURLConnection 所具備的方法,并且更強(qiáng)大腋妙。2015年NSURLConnection開始被廢棄了, 所以直接上NSURLSession的子類NSURLSessionDownloadTask;
// 當(dāng)前會話
@property (strong, nonatomic) NSURLSession *currentSession;
----------------------------------------------
// 可恢復(fù)的下載任務(wù)
@property (strong, nonatomic) NSURLSessionDownloadTask *resumableTask;
// 用于可恢復(fù)的下載任務(wù)的數(shù)據(jù)
@property (strong, nonatomic) NSData *partialData;
---------------------------------------------
#pragma mark 暫停/繼續(xù)下載
- (IBAction)suspendDownload:(id)sender {
//在此對該按鈕做判斷
if (self.judgeSuspend) {
[self.suspendBtn setTitle:@"繼續(xù)下載" forState:UIControlStateNormal];
self.judgeSuspend = NO;
[self suspendDown];
}else{
[self.suspendBtn setTitle:@"暫停下載" forState:UIControlStateNormal];
self.judgeSuspend = YES;
[self startResumableDown];
}
}
以上步驟其實(shí)像數(shù)據(jù)持久化的那一層一樣, 先判斷本地?cái)?shù)據(jù), 然后在做是否從網(wǎng)絡(luò)獲取的操作.但前提是, 退出/暫停時(shí)必須將下載的數(shù)據(jù)保存起來以便后續(xù)使用.
以下展示了繼續(xù)下載和暫停下載的代碼:
//繼續(xù)下載
- (void)startResumableDown{
if (!self.resumableDownloadTask) {
// 如果是之前被暫停的任務(wù)默怨,就從已經(jīng)保存的數(shù)據(jù)恢復(fù)下載
if (self.resumableData) {
self.resumableDownloadTask = [self.currentSession downloadTaskWithResumeData:self.resumableData];
}else {
// 否則創(chuàng)建下載任務(wù)
NSString *imageURLStr = @"http://dlsw.baidu.com/sw-search-sp/soft/9d/25765/sogou_mac_32c_V3.2.0.1437101586.dmg";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];
self.resumableDownloadTask = [self.currentSession downloadTaskWithRequest:request];
}
//關(guān)閉所有的按鈕的相應(yīng)
[self setDownloadButtonsWithEnabled:NO];
self.suspendBtn.enabled = YES;
self.imageView.image = nil;
[self.resumableDownloadTask resume];
}
}
//暫停下載
- (void)suspendDown{
if (self.resumableDownloadTask) {
[self.resumableDownloadTask cancelByProducingResumeData:^(NSData *resumeData) {
// 如果是可恢復(fù)的下載任務(wù),應(yīng)該先將數(shù)據(jù)保存到partialData中骤素,注意在這里不要調(diào)用cancel方法
self.resumableData = resumeData;
self.resumableDownloadTask = nil;
}];
}
}
第五. 實(shí)現(xiàn)后臺下載----下載較大文件
第一步, 不變的初始化
#pragma mark 后臺下載
- (IBAction)backDownload:(id)sender {
NSString *imageURLStr = @"http://dlsw.baidu.com/sw-search-sp/soft/9d/25765/sogou_mac_32c_V3.2.0.1437101586.dmg";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];
self.backDownloadTask = [self.backgroundSession downloadTaskWithRequest:request];
[self setDownloadButtonsWithEnabled:NO];
[self.backDownloadTask resume];
}
第二步: 對于獲取數(shù)據(jù)的地方
/* 完成下載任務(wù)匙睹,只有下載成功才調(diào)用該方法 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSLog(@"NSURLSessionDownloadDelegate: Finish downloading");
NSLog(@"----%@", [NSThread currentThread]);
// 1.將下載成功后的文件<在tmp目錄下>移動到目標(biāo)路徑
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileArray = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *destinationPath = [fileArray.firstObject URLByAppendingPathComponent:[location lastPathComponent]];
//在此有個下載文件后綴的問題
NSLog(@"----路徑--%@/n---%@", destinationPath.path, location);
if ([fileManager fileExistsAtPath:[destinationPath path] isDirectory:NULL]) {
[fileManager removeItemAtURL:destinationPath error:NULL];
}
//2將下載默認(rèn)的路徑移植到指定的路徑
NSError *error = nil;
if ([fileManager moveItemAtURL:location toURL:destinationPath error:&error]) {
self.progressView.progress = 1.0;
//刷新視圖,顯示下載后的圖片
UIImage *image = [UIImage imageWithContentsOfFile:[destinationPath path]];
WeakSelf;
//回主線程
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.imageView.image = image;
});
}
[self setDownloadButtonsWithEnabled:YES];
// 3.取消已經(jīng)完成的下載任務(wù)
if (session == self.backgroundSession) {
self.backDownloadTask = nil;
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
//需要在APPDelegate中做相應(yīng)的處理
if (appDelegate.backgroundURLSessionCompletionHandler) {
// 執(zhí)行回調(diào)代碼塊
void (^handler)() = appDelegate.backgroundURLSessionCompletionHandler;
appDelegate.backgroundURLSessionCompletionHandler = nil;
handler();
}
}
因?yàn)槭呛笈_處理, 因此需要在程序入口做處理
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
/* 用于保存后臺下載任務(wù)完成后的回調(diào)代碼塊 */
@property (copy) void (^backgroundURLSessionCompletionHandler)();
@end
---
#import "AppDelegate.h"
/* 后臺下載任務(wù)完成后济竹,程序被喚醒痕檬,該方法將被調(diào)用 */
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
NSLog(@"Application Delegate: Background download task finished");
// 設(shè)置回調(diào)的完成代碼塊
self.backgroundURLSessionCompletionHandler = completionHandler;
}
參考:
淺析 iOS 應(yīng)用開發(fā)中的斷點(diǎn)續(xù)傳
更多精彩內(nèi)容請關(guān)注“IT實(shí)戰(zhàn)聯(lián)盟”哦~~~