第五十六篇、OC打开本地和网络上的word、ppt、excel、text等文件
iOS打开本地和网络上的word、ppt、excel、text等文件
iOS开发过程中可能需要预览一些文件,这些文件的格式可能有word、ppt、excel等文件格式。那么系统提供两个类去预览这些文件,这两个类分别为QLPreviewController和UIDocumentInteractionController。
一、先看QLPreviewController怎么用
1.导入头文件 import < QuickLook/QuickLook.h >
2.创建一个继承QuickLookViewController继承UIViewController
3.遵守协议< QLPreviewControllerDataSource, QLPreviewControllerDelegate >
.h文件中的代码
# import < UIKit/UIKit.h >
# import < QuickLook/QuickLook.h > @interface QuickLookViewController : UIViewController < QLPreviewControllerDataSource,
QLPreviewControllerDelegate >
@property (nonatomic,strong) QLPreviewController *previewController;
@property (nonatomic,retain)NSURL *fileURL; @end
.m文件中的代码:
# import “QuickLookViewController.h” @interface QuickLookViewController () @end @implementation QuickLookViewController
@synthesize previewController = _previewController; (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @”附件预览”;
_previewController = [[QLPreviewController alloc] init];
_previewController.dataSource = self;
_previewController.delegate = self; _previewController.view.frame = CGRectMake(, , self.view.frame.size.width , self.view.frame.size.height);
_previewController.currentPreviewItemIndex = ;
// [self addChildViewController:_previewController];
[self.view addSubview:_previewController.view];
[_previewController reloadData]; }
- (id ) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index{
return self.fileURL;
}
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
return ;
}
@end
这样我们就完成了这个QuickLookViewController,使用:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@”Reader” ofType:@”pdf”];
NSURL *URL = [NSURL fileURLWithPath:filePath];
QuickLookViewController *quickLookVC = [[QuickLookViewController alloc]init];
quickLookVC.fileURL = URL;//本地图片的url
[self.navigationController pushViewController:quickLookVC animated:YES];
二、再看UIDocumentInteractionController
1.建立一个DocumentInteractionViewController,继承UIViewController
2.遵守代理UIDocumentInteractionControllerDelegate。
.h里面的代码
# import < UIKit/UIKit.h > @interface DocumentInteractionViewController : UIViewController< UIDocumentInteractionControllerDelegate,UIAlertViewDelegate >
@property(nonatomic,strong) UIDocumentInteractionController *documentInteractionController;
- (void)openFileWithURL:(NSURL *)URL;
@end
.m里面的代码
# import “DocumentInteractionViewController.h” @interface DocumentInteractionViewController ()
{
NSURL *_fileURL;
BOOL _isPreview;
BOOL _isOpenInMenu;
}
@end @implementation DocumentInteractionViewController (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor]; self.navigationController.navigationBarHidden = YES; }
- (void)openFileWithURL:(NSURL *)URL
{
NSLog(@”now open %@”,URL);
if (URL) {
_fileURL = URL;
_isPreview = NO;
_isOpenInMenu = NO;
// Initialize Document Interaction Controller
self.documentInteractionController = [UIDocumentInteractionController
interactionControllerWithURL:URL];
// Configure Document Interaction Controller
self.documentInteractionController.delegate = self;
// Preview File
[self.documentInteractionController presentPreviewAnimated:YES]; [NSTimer scheduledTimerWithTimeInterval: target:self selector:@selector(checkPreview) userInfo:nil repeats:NO];
}
} (void)checkPreview
{
if(_isPreview == NO)
{
if (_fileURL) {
// Initialize Document Interaction Controller
self.documentInteractionController = [UIDocumentInteractionController
interactionControllerWithURL:_fileURL];
// Configure Document Interaction Controller
self.documentInteractionController.delegate = self;
// Present Open In Menu
[self.documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES]; [NSTimer scheduledTimerWithTimeInterval: target:self selector:@selector(checkOpenInMenu) userInfo:nil repeats:NO];
}
}
} (void)checkOpenInMenu{
if(_isOpenInMenu == NO)
{
[self showWarning];
[[UIApplication sharedApplication]openURL:_fileURL];
}
} (void)showWarning{
NSString *fileType = [[_fileURL.absoluteString componentsSeparatedByString:@”.”]lastObject]; UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@”出错提示” message:[NSString stringWithFormat:@”不支持%@格式,请下载相关播放器打开”,fileType] delegate:self cancelButtonTitle:@”确定” otherButtonTitles:nil];
[alert show]; } (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
[self.navigationController popViewControllerAnimated:YES];
}
(UIViewController )documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController )controller{
return self;
}
// Preview presented/dismissed on document. Use to set up any HI underneath.
- (void)documentInteractionControllerWillBeginPreview:(UIDocumentInteractionController *)controller{
controller.name = @”附件预览”;
NSLog(@”willBeginPreview”);
_isPreview = YES;
} (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller{
NSLog(@”didEndPreview”);
[self.navigationController popViewControllerAnimated:YES];
}
// Options menu presented/dismissed on document. Use to set up any HI underneath.
- (void)documentInteractionControllerWillPresentOptionsMenu:(UIDocumentInteractionController *)controller{
NSLog(@”willPresentOptionsMenu”);
} (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller{
NSLog(@”didDismissOptionsMenu”);
}
// Open in menu presented/dismissed on document. Use to set up any HI underneath.
- (void)documentInteractionControllerWillPresentOpenInMenu:(UIDocumentInteractionController *)controller{
NSLog(@”willPresentOpenInMenu”);
_isOpenInMenu = YES;
}
- (void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller{
NSLog(@”didDismissOpenInMenu”);
[self.navigationController popViewControllerAnimated:YES];
}
@end 这样我们就完成了这个DocumentInteractionViewController,再来看用的时候怎么写:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@”Reader” ofType:@”pdf”];
NSURL *URL = [NSURL fileURLWithPath:filePath]; DocumentInteractionViewController *documentVC = [[DocumentInteractionViewController alloc]init];
[documentVC openFileWithURL:URL]; //本地文件的URL
[self.navigationController pushViewController:documentVC animated:YES];
上面讲的都是打开的本地的文件,那么我如果要预览一个网页上的资源呢?类似这样的URL http://weixintest.ihk.cn/ihkwx_upload/1.pdf ,怎么办?
理论是这样的,第一次预览,我们要下载到本地,然后打开这个资源,那么第n(n>1)次打开就从本地找到下载的这个资源直接打开就可以了。
那么我们要在我们的vc里面写一个UIWebView了。比如我们的vc就是OpenRemoteFileViewController,那么来看具体的代码实现
.h文件里面的代码
# import < UIKit/UIKit.h>
#import < QuickLook/QuickLook.h> @interface OpenRemoteFileViewController : UIViewController
@property (nonatomic, retain)NSString *fileURLString;
@end
.m文件里面的代码 #import “OpenRemoteFileViewController.h”
@interface OpenRemoteFileViewController () < UIWebViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate >{
UIWebView *openFileWebView; }
@property (nonatomic,strong)NSURL *fileURL; @end @implementation OpenRemoteFileViewController
-(void)openPDF:(UIButton *)sender{
openFileWebView = [[UIWebView alloc]initWithFrame:CGRectMake(, , self.view.frame.size.width, self.view.frame.size.height)];
openFileWebView.delegate = self;
[openFileWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.fileURLString]]];
}
- (void)viewDidLoad {
[super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor];
UIButton *centerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
centerBtn.backgroundColor = [UIColor orangeColor];
centerBtn.frame = CGRectMake(, , , );
centerBtn.center = self.view.center;
[centerBtn addTarget:self action:@selector(openPDF:) forControlEvents:UIControlEventTouchUpInside];
[centerBtn setTitle:@"打开一个远程PDF" forState:UIControlStateNormal];
[self.view addSubview:centerBtn];
}
- (BOOL)webView:(UIWebView )webView shouldStartLoadWithRequest:(NSURLRequest )request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
#pragma mark - Web代理
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSURL *targetURL = [NSURL URLWithString:self.fileURLString]; NSString *docPath = [self documentsDirectoryPath];
NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docPath, [targetURL lastPathComponent]];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL hasDownLoad= [fileManager fileExistsAtPath:pathToDownloadTo];
if (hasDownLoad) {
self.fileURL = [NSURL fileURLWithPath:pathToDownloadTo];
QLPreviewController *qlVC = [[QLPreviewController alloc]init];
qlVC.delegate = self;
qlVC.dataSource = self;
[self.navigationController pushViewController:qlVC animated:YES];
//
}
else {
NSURL *targetURL = [NSURL URLWithString:self.fileURLString]; NSData *fileData = [[NSData alloc] initWithContentsOfURL:targetURL];
// Get the path to the App's Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:]; // Get documents folder
[fileData writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, [targetURL lastPathComponent]] atomically:YES];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[openFileWebView loadRequest:request];
} NSLog(@"webViewDidFinishLoad");
} (void)webView:(UIWebView )webView didFailLoadWithError:(NSError )error
{
NSLog(@”didFailLoadWithError”);
} (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
return ;
} (id )previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
return self.fileURL;
} (void)previewControllerWillDismiss:(QLPreviewController *)controller {
NSLog(@”previewControllerWillDismiss”);
} (void)previewControllerDidDismiss:(QLPreviewController *)controller {
NSLog(@”previewControllerDidDismiss”);
} (BOOL)previewController:(QLPreviewController )controller shouldOpenURL:(NSURL )url forPreviewItem:(id )item{
return YES;
} (CGRect)previewController:(QLPreviewController )controller frameForPreviewItem:(id )item inSourceView:(UIView __nullable * __nonnull)view{
return CGRectZero;
} (NSString *)documentsDirectoryPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:];
return documentsDirectoryPath;
}
@end
使用:
OpenRemoteFileViewController *openRemoteFileVC =[[OpenRemoteFileViewController alloc]init];
openRemoteFileVC.fileURLString = @”http://weixintest.ihk.cn/ihkwx_upload/1.pdf“;//网络资源URL
[self.navigationController pushViewController:openRemoteFileVC animated:YES];
文章最后提供demo地址:https://github.com/zhengwenming/OpenFile
第五十六篇、OC打开本地和网络上的word、ppt、excel、text等文件的更多相关文章
- 第五十六篇:webpack的loader(四) -打包js中的高级语法
好家伙, 1.打包处理js文件中的高级语法 webpack只能打包处理一部分高级的JavaScript 语法.对于那些webpack无法处理的高级js 语法,需要借 助于 babel-loader 进 ...
- 《手把手教你》系列技巧篇(五十六)-java+ selenium自动化测试-下载文件-上篇(详细教程)
1.简介 前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件.因此宏哥就接着讲解和分享一下:自动化测试下载文件.可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就 ...
- 【Visual C++】游戏开发五十六 浅墨DirectX教程二十三 打造游戏GUI界面(一)
本系列文章由zhmxy555(毛星云)编写,转载请注明出处. 文章链接:http://blog.csdn.net/poem_qianmo/article/details/16384009 作者:毛星云 ...
- 跟我学SpringCloud | 第十六篇:微服务利剑之APM平台(二)Pinpoint
目录 SpringCloud系列教程 | 第十六篇:微服务利剑之APM平台(二)Pinpoint 1. Pinpoint概述 2. Pinpoint主要特性 3. Pinpoint优势 4. Pinp ...
- Egret入门学习日记 --- 第十六篇(书中 6.10~7.3节 内容)
第十六篇(书中 6.10~7.3节 内容) 昨天搞定了6.9节,今天就从6.10节开始. 其实这个蛮简单的. 这是程序员模式. 这是设计师模式. 至此,6.10节 完毕. 开始 6.11节. 有点没营 ...
- Python之路【第十六篇】:Django【基础篇】
Python之路[第十六篇]:Django[基础篇] Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了O ...
- 解剖SQLSERVER 第十六篇 OrcaMDF RawDatabase --MDF文件的瑞士军刀(译)
解剖SQLSERVER 第十六篇 OrcaMDF RawDatabase --MDF文件的瑞士军刀(译) http://improve.dk/orcamdf-rawdatabase-a-swiss-a ...
- 第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy分布式爬虫要点
第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy分布式爬虫要点 1.分布式爬虫原理 2.分布式爬虫优点 3.分布式爬虫需要解决的问题
- “全栈2019”Java第五十六章:多态与字段详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
随机推荐
- oracle备份恢复之rman恢复到异机
注意事项: 1 此处实验环境为同平台,同字节序,同版本,源机器和目标机器相同的目录结构. 2 目标机器只需要安装oracle数据库软件即可. 3 第一次利用备份恢复测试环境,之后从源机器拷贝备份到目标 ...
- ADO.NET 快速入门(十四):使用 SQL Server 检索数据
SqlDataReader 类提供了一种从数据源读取数据记录只进流的方法.如果想使用 OLE DB 接口的数据库或者 SQL Server7.0 之前的版本,请参考文章:使用 OLE DB 检索数据. ...
- iOS开发笔记系列-基础7(C语言特性)
Objective-C是C语言的扩展,因此,也具备很多C语言的基本特性,这里只罗列部分. 块(Blocks) 块是对C语言的一种扩展,它并未作为标准ANSI C所定义的部分,而是Apple添加到语言中 ...
- 元数据标签Embed
关于Embed外部资源的使用方法总结 Flex软件中经常需要使用一些外部的资源,如图片.声音.SWF或字体,虽然你也可以在软件运行的时候引入和载入,但是也可能经常需要直接将这些资源编译(Compile ...
- mysql 5.6 binlog组提交1
[MySQL 5.6] MySQL 5.6 group commit 性能测试及内部实现流程 尽管Mariadb以及Facebook在long long time ago就fix掉了这个臭名昭著的 ...
- 三大文本处理工具grep、sed及awk的简单介绍
grep.sed和awk都是文本处理工具,虽然都是文本处理工具单却都有各自的优缺点,一种文本处理命令是不能被另一个完全替换的,否则也不会出现三个文本处理命令了.只不过,相比较而言,sed和awk功能更 ...
- Ruby on Rails Tutorial 第二章 之 微博资源
1.微博模型如下图所示: 2.创建微博资源,命令如下: $ rails generate scaffold Micropost content:text user_id:integer #生成微博资 ...
- C++的64位整数
在做ACM题时,经常都会遇到一些比较大的整数.而常用的内置整数类型常常显得太小了:其中long 和 int 范围是[-2^31,2^31),即-2147483648~2147483647.而unsig ...
- MYSQL查询今天昨天本周本月等的数据
mysql查询本季度 今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天 SELECT *FROM表名WHERE TO_DAYS ...
- Helpers\Hooks
Helpers\Hooks Add modules with hooks The hooks helper allows modules to be created within the module ...