iOS開發網絡篇之TZHFileManager使用介紹,文件附件下載、大文件下載、斷點下載,下載至本地的本地文件查看,內存大小顯示與刪除

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

screenshot.png

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

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

import <Foundation/Foundation.h>

@interface TZHDownloadManager : NSObject

@property(nonatomic,strong)NSString *fileName;

+(instancetype)shared;

//異步下載的方法 進度的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;

//顯示文件占內存大小
+(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{
//保存下載任務對應的進度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];
        //把取消成功的結果返回
        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(@"文件已經存在");
    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

下載的管理類寫好之后 只需要在需要調用的地方調用相應的接口方法就可以了,

//異步下載的方法 進度的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;

//顯示文件占內存大小

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

+(void)deleteFileFromCache;

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

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

以下po出最終的實現效果:

動圖.gif

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

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

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容