iOS实现下载文件并预览(例如:word文件)

提前注释:下载方法出处在哪,我就不得而知了,不得而知了
我是复制项目里的代码,陈年往事不在查出处了,
看到的伙伴如果看到了原文,请联系我,我及时注明,🙏
-------分隔线----------
文章里的代码块,可直接复制到程序里使用
增加如下代理:

NSURLSessionDownloadDelegate,UIWebViewDelegate,UIDocumentInteractionControllerDelegate
/**
 *  下载任务
 */
@property (nonatomic, strong) NSURLSessionDownloadTask* downloadTask;
/**
 *  resumeData记录下载位置
 */
@property (nonatomic, strong) NSData* resumeData;
/**
 *  session
 */
@property (nonatomic, strong) NSURLSession* session;

源生session网络请求,点击方法里写👇这段代码,开始下载文件

//分解下载,大文件时使用
            NSURL* url = [NSURL URLWithString:noteModel.contractFileUrl];
            // 创建任务
            self.downloadTask = [self.session downloadTaskWithURL:url];
            // 开始任务
            [self.downloadTask resume];

session的懒加载

- (NSURLSession *)session
{
    if (nil == _session) {
        
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

下载完毕会调用NSURLSessionDownloadDelegate

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    // 将临时文件剪切或者复制Caches文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    // AtPath : 剪切前的文件路径
    // ToPath : 剪切后的文件路径
    //location  文件临时地址
    [mgr moveItemAtPath:location.path toPath:file error:nil];

    [Utils hideLoding:self.view];
/*
    // 提示下载完成
    [[[UIAlertView alloc] initWithTitle:@"下载完成" message:downloadTask.response.suggestedFilename delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil] show];
    */
    //文件路径
    NSString *cachePath = file;
/*
 /var/mobile/Containers/Data/Application/--/Library/Caches/888.docx
下面这段代码是调起预览
 */
    UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:cachePath]];
    
    documentController.delegate = self;
 
    //直接显示预览
    [documentController presentPreviewAnimated:YES];
    //显示包含预览的菜单项
    //[documentController presentOptionsMenuFromRect:CGRectZero inView:self.view animated:YES];
    //显示不包含预览菜单项
    [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    
}

在这里面监听下载进度,totalBytesWritten/totalBytesExpectedToWrite
每次写入沙盒完毕调用
bytesWritten 这次写入的大小
totalBytesWritten 已经写入沙盒的大小
totalBytesExpectedToWrite 文件总大小

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten
                        totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
   // NSLog((@"\n[函数名:%s]\n" "[行号:%d]\n" "%f\n"), __FUNCTION__, __LINE__,(double)totalBytesWritten/totalBytesExpectedToWrite);
    
}

👇调用预览的代理方法

- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller
{
    return self;
}
- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller
{
    return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller
{
    return self.view.frame;
}

点击预览窗口的“Done”(完成)按钮时调用

- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController*)_controller
{
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 使用NSURLConnection实现下载 1. 小文件下载 第一种方式(NSData) 第二种方式(NSURLC...
    搁浅的青蛙阅读 5,955评论 3 10
  • iOS开发中经常会用到文件的下载与上传功能,今天咱们来分享一下文件下载的思路。文件上传下篇再说。 文件下载分为小文...
    勤奋的笨老头阅读 57,142评论 61 459
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,445评论 30 472
  • JSON数据解析: JSON的简单介绍:什么是JSONJSON以一种轻量级的数据格式,一般用来数据交互服务器返回给...
    木子尚武阅读 2,555评论 0 0
  • 文‖大漠烟云 杯中的液体 喝下去是情怀 ·· 走过大唐长安街头 我体内的河流 涌出雄风 ·· 浅醉 深醉 一种...
    大漠烟云阅读 2,523评论 1 1

友情链接更多精彩内容