iOS下載之NSURLSessionDownloadTask

下載管理

DownloadManager.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

typedef void(^DownloadProgressBlock)(float progress);
typedef void(^DownloadCompleteBlock)(BOOL success, NSString * _Nullable filePath, NSError * _Nullable error);

@interface DownloadManager : NSObject

- (void)downloadWithUrl:(NSURL *)url toPath:(NSString *)toPath progress:(DownloadProgressBlock)progress complete:(DownloadCompleteBlock)complete;

- (void)cancel;
- (void)suspend;
- (void)resume;

@end

DownloadManager.m

#import "DownloadManager.h"

@interface DownloadManager () <NSURLSessionDelegate>

@property (nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;

@property (nonatomic, copy) DownloadProgressBlock progress;
@property (nonatomic, copy) DownloadCompleteBlock complete;

@property (nonatomic, strong) NSURL *fileUrl;
@property (nonatomic, strong) NSString *toPath;

@end

@implementation DownloadManager

#define ImageURL @"http://p3.so.qhimg.com/t01bddfda09bdfc39a3.jpg" //test

- (void)downloadWithUrl:(NSURL *)url toPath:(NSString *)toPath progress:(DownloadProgressBlock)progress complete:(DownloadCompleteBlock)complete
{
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.sessionConfiguration = sessionConfiguration;
        
    NSURLSession *downloadSession = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    self.session = downloadSession;
    
    //test
//    url = [NSURL URLWithString:ImageURL];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *downloadTask =  [downloadSession downloadTaskWithRequest:request];
    self.downloadTask = downloadTask;
    
    self.fileUrl = url;
    self.toPath = toPath;
    self.progress = progress;
    self.complete = complete;
    
    [downloadTask resume];
}

- (void)cancel
{
    if (self.downloadTask) {
        [self.downloadTask cancel];
    }
}

- (void)suspend
{
    if (self.downloadTask) {
        [self.downloadTask suspend];
    }
}

- (void)resume
{
    if (self.downloadTask) {
        [self.downloadTask resume];
    }
}

#pragma mark - NSURLSessionDelegate

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"app: bytesWritten=%@,totalBytesWritten=%@,totalBytesExpectedToWrite=%@",@(bytesWritten),@(totalBytesWritten),@(totalBytesExpectedToWrite));
    float progress = (float)totalBytesWritten/totalBytesExpectedToWrite;
    
    if (self.progress) {
        self.progress(progress);
    }
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"任務(wù)下載完成");
    if (self.progress) {
        self.progress(1.0);
    }
    
    //1 拼接文件全路徑
    if (self.toPath.length) {
        if (self.toPath.lastPathComponent.length) {
            //do nothing
        } else {
            self.toPath = [self.toPath stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
        }
    } else {
        //默認(rèn)下載到/Library/Cache/SavedFiles
        NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        NSString *appDir = [cacheDir stringByAppendingPathComponent:@"SavedFiles"];
        self.toPath = [appDir stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    }
    
    //2 必須要剪切文件, 因?yàn)橄到y(tǒng)默認(rèn)會(huì)刪除
    if ([[NSFileManager defaultManager] fileExistsAtPath:self.toPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:self.toPath error:nil];
    }
    //創(chuàng)建文件夾
    NSString *dir = [self.toPath stringByDeletingLastPathComponent];
    BOOL isDir = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:dir isDirectory:&isDir]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    [[NSFileManager defaultManager]moveItemAtURL:location toURL:[NSURL fileURLWithPath:self.toPath] error:nil];
    NSLog(@"app: download ok, path:%@", self.toPath);
}

//無(wú)論是數(shù)據(jù)任務(wù)還是上傳任務(wù)執(zhí)行完之后都會(huì)執(zhí)行該回調(diào)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"整個(gè)任務(wù)完成");
    NSLog(@"app: download complete, error:%@", error);
    if (error) {
        // check if resume data are available
        if ([error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData]) {
            NSData *resumeData = [error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData];
            //通過(guò)之前保存的resumeData盆偿,獲取斷點(diǎn)的NSURLSessionTask钱雷,調(diào)用resume恢復(fù)下載
//            self.resumeData = resumeData;
            //彈出提示框壁酬,如果需要重新下載巷查,則調(diào)用[download taskwithResumeData]
        }
    } else {
       //下載完成處理
    }
    
    if (self.complete) {
        self.complete(error ? NO : YES, error ? nil : self.toPath, error);
    }
}

@end

下載調(diào)用

SYDownloadManager *manager = [[SYDownloadManager alloc] init];
    [manager downloadWithUrl:[NSURL URLWithString:url] toPath:toPath progress:^(float progress) {
         //other things
    } complete:^(BOOL success, NSString * _Nullable filePath, NSError * _Nullable error) {
        if (self.completeCallback) {
            NSDictionary *dic = error ? @{
                @"code" : @(error.code),
                @"success" : @(success),
                @"errMsg" : error.userInfo.description ? error.userInfo.description : @""
            } : @{
                @"success" : @(success),
                @"filePath" : filePath,
            };

          //other things
        }
    }];
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市绪爸,隨后出現(xiàn)的幾起案子蛉拙,更是在濱河造成了極大的恐慌界睁,老刑警劉巖觉增,帶你破解...
    沈念sama閱讀 222,681評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異翻斟,居然都是意外死亡逾礁,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門访惜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)嘹履,“玉大人,你說(shuō)我怎么就攤上這事债热±担” “怎么了?”我有些...
    開封第一講書人閱讀 169,421評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵窒篱,是天一觀的道長(zhǎng)焕刮。 經(jīng)常有香客問(wèn)我,道長(zhǎng)墙杯,這世上最難降的妖魔是什么配并? 我笑而不...
    開封第一講書人閱讀 60,114評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮高镐,結(jié)果婚禮上溉旋,老公的妹妹穿的比我還像新娘。我一直安慰自己嫉髓,他們只是感情好观腊,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,116評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著岩喷,像睡著了一般恕沫。 火紅的嫁衣襯著肌膚如雪监憎。 梳的紋絲不亂的頭發(fā)上纱意,一...
    開封第一講書人閱讀 52,713評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音鲸阔,去河邊找鬼偷霉。 笑死,一個(gè)胖子當(dāng)著我的面吹牛褐筛,可吹牛的內(nèi)容都是我干的类少。 我是一名探鬼主播,決...
    沈念sama閱讀 41,170評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼渔扎,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼硫狞!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,116評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤残吩,失蹤者是張志新(化名)和其女友劉穎财忽,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體泣侮,經(jīng)...
    沈念sama閱讀 46,651評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡即彪,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,714評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了活尊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片隶校。...
    茶點(diǎn)故事閱讀 40,865評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖蛹锰,靈堂內(nèi)的尸體忽然破棺而出深胳,到底是詐尸還是另有隱情,我是刑警寧澤铜犬,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布稠屠,位于F島的核電站,受9級(jí)特大地震影響翎苫,放射性物質(zhì)發(fā)生泄漏权埠。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,211評(píng)論 3 336
  • 文/蒙蒙 一煎谍、第九天 我趴在偏房一處隱蔽的房頂上張望攘蔽。 院中可真熱鬧,春花似錦呐粘、人聲如沸满俗。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)唆垃。三九已至,卻和暖如春痘儡,著一層夾襖步出監(jiān)牢的瞬間辕万,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工沉删, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留渐尿,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,299評(píng)論 3 379
  • 正文 我出身青樓矾瑰,卻偏偏與公主長(zhǎng)得像砖茸,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子殴穴,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,870評(píng)論 2 361

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