0
点赞
收藏
分享

微信扫一扫

iOS开发中下载Word文件并打开预览(可用三方软件打开)

飞鸟不急 2021-09-29 阅读 48
效果图

思路

先下载再打开
1.用AF下载文件
2.用UIDocumentInteractionController打开Word文件

核心代码:

  /**
下载文件

@param docPath 文件路径
@param fileName 文件名
*/

-(void)downloadDocxWithDocPath:(NSString *)docPath fileName:(NSString *)fileName {

NSString *urlString = downloadString;
NSURL * url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

NSLog(@"%lld %lld",downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

NSString *path = [docPath stringByAppendingPathComponent:fileName];
return [NSURL fileURLWithPath:path]; //这里返回的是文件下载到哪里的路径 要注意的是必须是携带协议file://
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

NSString *name = [filePath path];
[self openDocxWithPath:name];
}];
[task resume];

}

-(void)openDocxWithPath:(NSString *)filePath {
NSLog(@"%s", __func__);
UIDocumentInteractionController *doc= [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
doc.delegate = self;
[doc presentPreviewAnimated:YES];
// 打开的过程有点慢
}

我们可以把下载的文件放在沙盒中Documents文件一个自己创建的文件下,以便我们统一一次性将下载的所有Word文件全部删除掉。

demo地址: *** https://gitee.com/liangsenliangsen/download_word.git

****本篇文章到这里就结束了,愿大家加班不多工资多,男同胞都有女朋友,女同胞都有男朋友。?***

举报

相关推荐

0 条评论