iOS網(wǎng)絡(luò)----簡單下載/斷點(diǎn)續(xù)傳/后臺下載

目錄

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ù), 并下載一個圖片展示出來;

效果圖為

Paste_Image.png
#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;
}

Demo地址---iOSDownload


參考:
淺析 iOS 應(yīng)用開發(fā)中的斷點(diǎn)續(xù)傳

更多精彩內(nèi)容請關(guān)注“IT實(shí)戰(zhàn)聯(lián)盟”哦~~~


IT實(shí)戰(zhàn)聯(lián)盟.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市送浊,隨后出現(xiàn)的幾起案子梦谜,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件唁桩,死亡現(xiàn)場離奇詭異闭树,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)朵夏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進(jìn)店門蔼啦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人仰猖,你說我怎么就攤上這事∧巫眩” “怎么了饥侵?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長衣屏。 經(jīng)常有香客問我躏升,道長,這世上最難降的妖魔是什么狼忱? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任膨疏,我火速辦了婚禮,結(jié)果婚禮上钻弄,老公的妹妹穿的比我還像新娘佃却。我一直安慰自己,他們只是感情好窘俺,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布饲帅。 她就那樣靜靜地躺著,像睡著了一般瘤泪。 火紅的嫁衣襯著肌膚如雪灶泵。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天对途,我揣著相機(jī)與錄音赦邻,去河邊找鬼。 笑死实檀,一個胖子當(dāng)著我的面吹牛惶洲,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播劲妙,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼湃鹊,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了镣奋?” 一聲冷哼從身側(cè)響起币呵,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后余赢,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體芯义,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年妻柒,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了扛拨。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡举塔,死狀恐怖绑警,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情央渣,我是刑警寧澤计盒,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站芽丹,受9級特大地震影響北启,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜拔第,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一咕村、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蚊俺,春花似錦懈涛、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至暂殖,卻和暖如春价匠,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背呛每。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工踩窖, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人晨横。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓洋腮,卻偏偏與公主長得像,于是被迫代替她去往敵國和親手形。 傳聞我的和親對象是個殘疾皇子啥供,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容