在項(xiàng)目里遇到附件的下載和本地查看功能,附件有可能是word pdf 圖片 Excel表格 甚至是ppt 有點(diǎn)變態(tài)吧,大致就是點(diǎn)擊下圖的附件按鈕然后查看附件:
實(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ì)過程
以下po出最終的實(shí)現(xiàn)效果:
之前在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)不易啊 !覺得好用 喜歡的話記得給我打星呀 ??