在项目里遇到附件的下载和本地查看功能,附件有可能是word pdf 图片 Excel表格 甚至是ppt 有点变态吧,大致就是点击下图的附件按钮然后查看附件:
实现起来的具体思路就是文件的下载,和下载好的本地文件的查看两部分. 本人还是比较懒的,所以去著名的程序员单身交友网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来实现的,这个在之前的文章里已经说过了实现原理了 有兴趣的老铁可以点击底下的这个链接,查看实现的详细过程
以下po出最终的实现效果:
之前在github上没有找到合适的框架,所以自己封装了一个文件下载与查看的框架 放到了github上供大家下载,有详细的demo 使用直接把TZHFileManager 拖进项目的资源路径下即可,集成也相当简单,只需要两步,demo里已做了详细的说明,有兴趣的老铁可以下载下来看看,欢迎给我提建议 QQ:734754688
github地址: https://github.com/TZHui/TZHFileManager
原创不易啊 !觉得好用 喜欢的话记得给我打星呀 😁