第五十六篇、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第 ...
随机推荐
- Volley使用指南第二回(来自developer.android)
上一篇文章翻译了一下google的Volley官方文档,讲到了最基本的发送request.这一次我们来下一回:创建一个自定义RequestQueue. 这篇文章将会教你一步一步创建自己的Request ...
- 关于Struts2的客户端校验的FreeMarker template error!
把<s:form action="login" namespace="/" validate="true" >改为 <s: ...
- 窗体 dialog 弹出时动画效果
1.先创建 anim中的 xml 动画文件 <?xml version="1.0" encoding="utf-8"? > <set x ...
- 学习JSONP
最近自己研究 跨域调用js,然后 发现 有jsonp 这种技术,在Jquery中可以使用,于是 研究下原理 发现: 其实 就是 利用<script>的跨域访问的能力. 调用 服务端 返回的 ...
- C++ 内存相关
1.C++的内存管理可分为以下几个部分: 栈:记录程序的执行过程. 堆:采用new,delete申请释放内存. 自由存储区:对应于C中使用malloc,free申请释放内存. 全局存储区:也叫静态存储 ...
- IOS Note - Core NS Data Types
NSString (Immutable)NSMutableString (rarely used)NSNumberNSValueNSData (bits)NSDateNSArray (Immutabl ...
- [AngularJS] Lazy Loading modules with ui-router and ocLazyLoad
We've looked at lazy loading with ocLazyLoad previously, but what if we are using ui-router and want ...
- Yii框架学习 新手教程(一)
本人小菜鸟一仅仅,为了自我学习和交流PHP(jquery,linux,lamp,shell,javascript,server)等一系列的知识,小菜鸟创建了一个群.希望光临本博客的人能够进来交流.寻求 ...
- 用Linux安装光盘修复GRUB
转载:http://lgn21st.iteye.com/blog/179455 需要开视频会议,我不得零时从Ubuntu切换回去百年难道用一次的WinXP...发现自己的XP系统很混乱...决定重新装 ...
- PHP.5-DIV+CSS布局网站首页实例
DIV+CSS布局网站首页实例 网站页面布局 http://www.sj33.cn/digital/wyll/201501/42379.html[页头.页脚.侧边栏和内容区域] #避免各浏览器对CSS ...