/// 下载/打开

- (void)downloadActionWithDownloadString:(NSString *)downloadString{

//url : 下载地址

NSString *url;

if ([downloadString containsString:@"?"]) {

NSRange range = [downloadString rangeOfString:@"?"];

url = [downloadString substringToIndex:range.location];

}else{

url = downloadString;

}

//suffix : 后缀.zip .doc

NSString * suffix = [url pathExtension];

NSMutableArray *tempArray = [NSMutableArray arrayWithArray:[url  componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/."]]];//@",!"以,或!切割,而不是把,!连在一起当成一个整体进行切割

NSInteger count = tempArray.count-2;

NSString *preName = tempArray[count];

//name : 文件名XXX.zip

NSString * name = [NSString stringWithFormat:@"%@.%@", preName,suffix];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths lastObject];

NSFileManager *fileManager = [NSFileManager defaultManager];

//创建一个本地沙盒文件,便于日后管理,比如删除

NSString * filesPath = [documentsDirectory stringByAppendingPathComponent:@"files"];

if (![[NSFileManager defaultManager] fileExistsAtPath:filesPath]) {

/// 创建一个文件

BOOL success =  [[NSFileManager defaultManager] createDirectoryAtPath:filesPath withIntermediateDirectories:YES attributes:nil error:nil];

NSLog(@"success:%d", success);

}

//filepath :下载后的文件本地路径

NSString *filePath = [filesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", name]];

if ([fileManager fileExistsAtPath:filePath]) {

//文件已经存在,直接打开

UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

[alertController addAction:cancelAction];

[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

[self openDocxWithPath:filePath];

}]];

[self presentViewController:alertController animated:YES completion:nil];

}else {

//文件不存在,要下载

UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否下载并打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

[alertController addAction:cancelAction];

[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

[self downloadDocxWithFilePath:filePath downloadString:downloadString];

}]];

[self presentViewController:alertController animated:YES completion:nil];

}

}

/**

下载文件

@param filePath 文件本地路径

@param downloadString 文件下载地址

*/

-(void)downloadDocxWithFilePath:(NSString *)filePath downloadString:(NSString *)downloadString{

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);

NSLog(@"下载中....");

} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

return [NSURL fileURLWithPath:filePath];  //这里返回的是文件下载到哪里的路径 要注意的是必须是携带协议file://

} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

NSString *name = [filePath path];

[self openDocxWithPath:name];

}];

[task resume];

}

/**

打开文件

@param filePath 文件路径

*/

-(void)openDocxWithPath:(NSString *)filePath {

UIDocumentInteractionController *doc= [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];

doc.delegate = self;

[doc presentPreviewAnimated:YES];

// 打开的过程有点慢

}

#pragma mark - UIDocumentInteractionControllerDelegate

//必须实现的代理方法 预览窗口以模式窗口的形式显示,因此需要在该方法中返回一个view controller ,作为预览窗口的父窗口。如果你不实现该方法,或者在该方法中返回 nil,或者你返回的 view controller 无法呈现模式窗口,则该预览窗口不会显示。

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{

return self;

}

- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller {

return self.view;

}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {

return CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height);

}

iOS OC开发,文件的下载、预览的更多相关文章

  1. 李洪强iOS开发之苹果使用预览截图

    李洪强iOS开发之苹果使用预览截图 01 在预览的图片中选中你要截得区域  02 - command + C   03 - Command + N 04 - Command + S (保存)

  2. 基于bootstrap的上传插件fileinput实现ajax异步上传功能(支持多文件上传预览拖拽)

    首先需要导入一些js和css文件 ? 1 2 3 4 5 6 <link href="__PUBLIC__/CSS/bootstrap.css" rel="exte ...

  3. atitit.javascript js 上传文件的本地预览

    atitit.javascript js 上传文件的本地预览 1. .URL.createObjectURL  1 1.1. 吊销所有使用 URL.createObjectURL 而创建的 URL,以 ...

  4. 前端vue实现pdf文件的在线预览

    3.前端vue实现pdf文件的在线预览 我是通过 <iframe> 标签就可以满足我工作的 pdf预览需求 如果<iframe> 无法满足需求 , 可以使用pdf.js这个插件 ...

  5. SpringBoot+FreeMarker开发word文档下载,预览

    背景: 开发一个根据模版,自动填充用户数据并下载word文档的功能 使用freemarker进行定义模版,然后把数据进行填充. maven依赖: <parent> <groupId& ...

  6. iOS开发之使用Storyboard预览UI在不同屏幕上的运行效果

    在公司做项目一直使用Storyboard,虽然有时会遇到团队合作的Storyboard冲突问题,但是对于Storyboard开发效率之高还是比较划算的.在之前的博客中也提到过,团队合作使用Storyb ...

  7. React + js-xlsx构建Excel文件上传预览功能

    首先要准备react开发环境以及js-xlsx插件 1. 此处省略安装react安装步骤 2.下载js-xlsx插件 yarn add xlsx 或者 npm install xlsx 在项目中引入 ...

  8. SVG-Android开源库——SVG生成Vector资源文件的编辑预览工具

    Vector矢量图在Android项目中的应用越来越广泛,但是如果你想用Android Studio自带的工具将SVG图片转化成Vector资源文件却是相当麻烦,首先能支持的SVG规范较少,其次操作流 ...

  9. 安卓开发实用技巧:TextView预览

    背景: 使用TextView时,为了方便在开发工具中预览效果,需要在TextView中设置文字(如:android:text="Hello World"),但是等到后面提交时,为了 ...

  10. iOS全埋点解决方案-界面预览事件

    前言 ​ 我们先了解 UIViewController 生命周期相关的内容和 iOS 的"黑魔法" Method Swizzling.然后再了解页面浏览事件($AppViewScr ...

随机推荐

  1. rxswift自定义扩展UI组件

    扩展UI组件时常用到的一些发布者与订阅者如下: 发布者: ControlEvent(专门用于描述 UI 控件所产生的事件) 订阅者(观察者): Binder(专门用于绑定UI状态的,如:当某个状态改变 ...

  2. ASR6601:国产化lora SOC芯片兼容SX1262/SX1268

    ASR6601为目前首颗国产化支持LoRaWAN低功耗广域网无线通信SoC芯片.ASR6601在单芯片上集成了通用微控制器和射频单元(SX1262),包括射频收发器,调制解调器和48 MHz 主频.A ...

  3. 数据表主键设置自增后插入数据的mabatis写法

    研究出两种写法,因为画蛇添足修改了好久. 下面写两种正确的. <insert id="Insert" parameterType="com.aged.www.Poj ...

  4. 【服务器数据恢复】raid5硬盘同步数据未完成时关机的数据恢复案例

    服务器数据恢复环境:某公司一台服务器组建了一组raid5磁盘阵列,作为共享存储池使用.该服务器存储数据库文件和普通文件. 服务器故障&检测:RAID5磁盘阵列的硬盘掉线导致服务器操作系统识别不 ...

  5. rt_raster_to_gdal: Could not load the output GDAL driver

    问题记录:postgis 安装后不能执行以下语句,查询入库的 tif 文件 SELECT ST_AsGDALRaster(rast, 'GTiff') As rastjpg FROM radar_da ...

  6. 【36oj】 画圣诞树

    原题 圣诞节要到了,不少商家在宣传板上绘制了圣诞树的图案,如图所示.一棵圣诞树由A和B两部分组成: A是由n(n≥)个呈三角形的字符矩阵构成的,每个字符矩阵由三个参数ai.bi.ci唯一确定.Ai表示 ...

  7. 模型admin 外键的相关操作

    ....@admin.register(MyModel)class MyModelAdmin(admin.ModelAdmin): def method(self, request, queryset ...

  8. ERROR 1862 (HY000): Your password has expired. To log in you must change it using a .....

    navcat 登录本地失败 https://blog.csdn.net/fenniang16/article/details/81216602?spm=1001.2101.3001.6661.1&am ...

  9. STM32F0 LL库IIC第二地址配置错误

    最近在做F0项目要用到多个IIC地址,使用Cube生成的LL库,第二地址进不了中断 F0版本:1.11.0 STM32CubeX生成的LL库代码为: 1 static void MX_I2C1_Ini ...

  10. 超2T硬盘使用gpt分区及做成lvm

    1.超过2T分区不能用fdisk了,用parted 分区格式化后对新的分区做lvm