iOS開發(fā)網(wǎng)絡(luò)篇之TZHFileManager使用介紹,文件附件下載饿序、大文件下載、斷點(diǎn)下載,下載至本地的本地文件查看,內(nèi)存大小顯示與刪除

在項(xiàng)目里遇到附件的下載和本地查看功能,附件有可能是word pdf 圖片 Excel表格 甚至是ppt 有點(diǎn)變態(tài)吧,大致就是點(diǎn)擊下圖的附件按鈕然后查看附件:

screenshot.png

實(shí)現(xiàn)起來的具體思路就是文件的下載,和下載好的本地文件的查看兩部分. 本人還是比較懶的,所以去著名的程序員單身交友網(wǎng)github上看看有沒有好用的第三方框架,下了好幾款,但是總結(jié)一下:都不太好用,所以就決定自己寫一個(gè)順手的.好了,廢話不多說,下面具體的闡述我是怎么實(shí)現(xiàn)的:(demo已上傳到github 點(diǎn)擊查看: https://github.com/TZHui/TZHFileManager)

最重要的是首先創(chuàng)建一個(gè)TZHDownloadManager文件下載管理類.下面直接po代碼,在.h文件中

import <Foundation/Foundation.h>

@interface TZHDownloadManager : NSObject

@property(nonatomic,strong)NSString *fileName;

+(instancetype)shared;

//異步下載的方法 進(jìn)度的block
-(void)downloadAudioWithURL:(NSURL *)url andFormat:(NSString *)format progress:(void(^)(float progress))progressBlock complete:(void(^)(NSString *fileSavePath,NSError *error))completeBlock;

//判斷是否正在下載
-(BOOL)isDownloadingAudioWithURL:(NSURL *)url;

//取消下載
-(void)cancelDownloadingAudioWithURL:(NSURL *)url andFormat:(NSString *)format complete:(void (^)())completeBlock;

//顯示文件占內(nèi)存大小
+(NSString *)getFileCacheSize;
//刪除文件

+(void)deleteFileFromCache;

@end

在TZHDownloadManager.m文件中

import "TZHDownloadManager.h"

import "NSString+Hash.h"

@interface TZHDownloadManager ()<NSURLSessionDownloadDelegate>

@property (nonatomic, strong) NSURLSession *session;
@property(nonatomic,strong)NSString *fileForm;

@end
@implementation TZHDownloadManager{
//保存下載任務(wù)對(duì)應(yīng)的進(jìn)度block 和 完成的block
NSMutableDictionary *_progressBlocks;
NSMutableDictionary *_completeBlocks;
NSMutableDictionary *_downloadTasks;
}

static id _instance;

+(instancetype)shared{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{
    _instance = [[self alloc] init];
});
return _instance;

}

-(instancetype)init {
self = [super init];

if (self) {
    _progressBlocks = [NSMutableDictionary dictionary];
    _completeBlocks = [NSMutableDictionary dictionary];
    _downloadTasks = [NSMutableDictionary dictionary];
}
return self;

}

-(NSURLSession *)session {
if (!_session) {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

    _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;

}

-(BOOL)isDownloadingAudioWithURL:(NSURL *)url {

if (_completeBlocks[url]) {
    return YES;
}
return NO;

}

-(void)cancelDownloadingAudioWithURL:(NSURL *)url andFormat:(NSString *)format complete:(void (^)())completeBlock {

NSURLSessionDownloadTask *currentTask = _downloadTasks[url];
// 2.cancel
if (currentTask) {
    [currentTask cancelByProducingResumeData:^(NSData *_Nullable resumeData) {
        [resumeData writeToFile:[self getResumeDataPathWithURL:url andFormat:format] atomically:YES];
        //把取消成功的結(jié)果返回
        if (completeBlock) {
          completeBlock();
       }
       _progressBlocks[url] = nil;
       _completeBlocks[url] = nil;
       _downloadTasks[url] = nil;
    }];
}

}

//入口
-(void)downloadAudioWithURL:(NSURL *)url andFormat:(NSString *)format progress:(void (^)(float progress))progressBlock complete:(void (^)(NSString *fileSavePath, NSError *error))completeBlock {

NSFileManager *fileMan = [NSFileManager defaultManager];
NSLog(@"下載工具中打印格式%@",format);
_fileForm = format;
NSString *fileSavePath = [self getFileSavePathWithURL:url andFormat:format];
if ([fileMan fileExistsAtPath:fileSavePath]) {
    NSLog(@"文件已經(jīng)存在");
    if (completeBlock) {
        completeBlock(fileSavePath, nil);
    }
    return;
}
if ([self isDownloadingAudioWithURL:url]) {
    NSLog(@"正在下載");
    return;
}
[_progressBlocks setObject:progressBlock forKey:url];
[_completeBlocks setObject:completeBlock forKey:url];
NSString *resumeDataPath = [self getResumeDataPathWithURL:url andFormat:format];
NSURLSessionDownloadTask *downloadTask;
if ([fileMan fileExistsAtPath:resumeDataPath]) {
    NSData *resumeData = [NSData dataWithContentsOfFile:resumeDataPath];
    downloadTask = [self.session downloadTaskWithResumeData:resumeData];
} else {
    downloadTask = [self.session downloadTaskWithURL:url];
}
[_downloadTasks setObject:downloadTask forKey:url];
//開啟
[downloadTask resume];

}

-(NSString *)getResumeDataPathWithURL:(NSURL *)url andFormat:(NSString *)format{
NSString *tmpPath = NSTemporaryDirectory();

NSString *fileName = [NSString stringWithFormat:@"%@%@",[url.absoluteString md5String],format];
return [tmpPath stringByAppendingPathComponent:fileName];

}

-(NSString *)getFileSavePathWithURL:(NSURL *)url andFormat:(NSString *)format{

NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *TZHCachePath = [cachePath stringByAppendingPathComponent:@"TZHDownloadFile"];
[fileManager createDirectoryAtPath:TZHCachePath withIntermediateDirectories:YES attributes:nil error:nil];

NSString *fileName = [NSString stringWithFormat:@"%@%@",[url.absoluteString md5String],format];
_fileName = fileName;
return [TZHCachePath stringByAppendingPathComponent:fileName];
}

// sessionDelegate 代理方法

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {

NSFileManager *fileMan = [NSFileManager defaultManager];

NSURL *currentURL = downloadTask.currentRequest.URL;
[fileMan copyItemAtPath:location.path toPath:[self getFileSavePathWithURL:currentURL andFormat:_fileForm] error:NULL];

if (_completeBlocks[currentURL]) {
    void (^tmpCompBlock)(NSString *filePath, NSError *error) = _completeBlocks[currentURL];
    tmpCompBlock([self getFileSavePathWithURL:currentURL andFormat:_fileForm], nil);
}
_progressBlocks[currentURL] = nil;
_completeBlocks[currentURL] = nil;
_downloadTasks[currentURL] = nil;

}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {

float progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
NSURL *url = downloadTask.currentRequest.URL;
if (_progressBlocks[url]) {
   void (^tmpProBlock)(float) = _progressBlocks[url];
   tmpProBlock(progress);
}

}

+(NSString *)getFileCacheSize{

NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *TZHCachePath = [cachePath stringByAppendingPathComponent:@"TZHDownloadFile"];
NSArray *subPathArr = [[NSFileManager defaultManager] subpathsAtPath:TZHCachePath];
NSString *filePath  = nil;
NSInteger totleSize = 0;
for (NSString *subPath in subPathArr){
    filePath =[TZHCachePath stringByAppendingPathComponent:subPath];
    BOOL isDirectory = NO;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
    if (!isExist || isDirectory || [filePath containsString:@".DS"]){
        continue;
    }
    
    NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    NSInteger size = [dict[@"NSFileSize"] integerValue];
    totleSize += size;
}
NSString *totleStr = nil;
if (totleSize > 1000 * 1000){
    totleStr = [NSString stringWithFormat:@"%.2fM",totleSize / 1000.00f /1000.00f];
}else if (totleSize > 1000){
    totleStr = [NSString stringWithFormat:@"%.2fKB",totleSize / 1000.00f ];
}else{
   totleStr = [NSString stringWithFormat:@"%.2fB",totleSize / 1.00f];
}
return totleStr;

}

+(void)deleteFileFromCache{

NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *TZHCachePath = [cachePath stringByAppendingPathComponent:@"TZHDownloadFile"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *array = [fileManager contentsOfDirectoryAtPath:TZHCachePath error:nil];
for(NSString *fileName in array){
    [fileManager removeItemAtPath:[TZHCachePath stringByAppendingPathComponent:fileName] error:nil];
}

}
@end

下載的管理類寫好之后 只需要在需要調(diào)用的地方調(diào)用相應(yīng)的接口方法就可以了,

//異步下載的方法 進(jìn)度的block
-(void)downloadAudioWithURL:(NSURL *)url andFormat:(NSString *)format progress:(void(^)(float progress))progressBlock complete:(void(^)(NSString *fileSavePath,NSError *error))completeBlock;

//判斷是否正在下載
-(BOOL)isDownloadingAudioWithURL:(NSURL *)url;

//取消下載

  • (void)cancelDownloadingAudioWithURL:(NSURL *)url andFormat:(NSString *)format complete:(void (^)())completeBlock;

//顯示文件占內(nèi)存大小

  • (NSString *)getFileCacheSize;
    //刪除文件

+(void)deleteFileFromCache;

實(shí)現(xiàn)了下載功能之后,需要做的就是如何把下載在本地沙盒文件給顯示出來了,樓主試過很多方法 有蘋果自備的api 但是都不好用,最后使用UIWebView來實(shí)現(xiàn)的,這個(gè)在之前的文章里已經(jīng)說過了實(shí)現(xiàn)原理了 有興趣的老鐵可以點(diǎn)擊底下的這個(gè)鏈接,查看實(shí)現(xiàn)的詳細(xì)過程

http://www.reibang.com/p/ee96475018ee

以下po出最終的實(shí)現(xiàn)效果:

動(dòng)圖.gif

之前在github上沒有找到合適的框架,所以自己封裝了一個(gè)文件下載與查看的框架 放到了github上供大家下載,有詳細(xì)的demo 使用直接把TZHFileManager 拖進(jìn)項(xiàng)目的資源路徑下即可,集成也相當(dāng)簡(jiǎn)單,只需要兩步,demo里已做了詳細(xì)的說明,有興趣的老鐵可以下載下來看看,歡迎給我提建議 QQ:734754688

github地址: https://github.com/TZHui/TZHFileManager

原創(chuàng)不易啊 !覺得好用 喜歡的話記得給我打星呀 ??

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末管嬉,一起剝皮案震驚了整個(gè)濱河市皂林,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蚯撩,老刑警劉巖础倍,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異胎挎,居然都是意外死亡沟启,警方通過查閱死者的電腦和手機(jī)扰楼,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來美浦,“玉大人弦赖,你說我怎么就攤上這事〉攀” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵流酬,是天一觀的道長币厕。 經(jīng)常有香客問我,道長芽腾,這世上最難降的妖魔是什么旦装? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮摊滔,結(jié)果婚禮上阴绢,老公的妹妹穿的比我還像新娘。我一直安慰自己艰躺,他們只是感情好呻袭,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著腺兴,像睡著了一般左电。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上页响,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天篓足,我揣著相機(jī)與錄音,去河邊找鬼闰蚕。 笑死栈拖,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的陪腌。 我是一名探鬼主播辱魁,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼烟瞧,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼诗鸭!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起参滴,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤强岸,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后砾赔,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蝌箍,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡青灼,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了妓盲。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片杂拨。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖悯衬,靈堂內(nèi)的尸體忽然破棺而出弹沽,到底是詐尸還是另有隱情,我是刑警寧澤筋粗,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布策橘,位于F島的核電站,受9級(jí)特大地震影響娜亿,放射性物質(zhì)發(fā)生泄漏丽已。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一买决、第九天 我趴在偏房一處隱蔽的房頂上張望沛婴。 院中可真熱鬧,春花似錦督赤、人聲如沸瘸味。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽旁仿。三九已至,卻和暖如春孽糖,著一層夾襖步出監(jiān)牢的瞬間枯冈,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來泰國打工办悟, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留尘奏,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓病蛉,卻偏偏與公主長得像炫加,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子铺然,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

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