第五十六篇、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第 ...
随机推荐
- cocos2d-x 让精灵按照自己设定的运动轨迹行动
转自:http://blog.csdn.net/ufolr/article/details/7447773 在cocos2d中,系统提供了CCMove.CCJump.CCBezier(贝塞尔曲线)等让 ...
- javascript keycode大全【转载】
keycode 8 = BackSpace BackSpace keycode 9 = Tab Tabkeycode 12 = Clearkeycode 13 = Enterkey ...
- WCF与WebService之间的异同
下面我们来详细讨论一下二者的区别.Web Service和WCF的到底有什么区别. 1,Web Service:严格来说是行业标准,也就是Web Service 规范,也称作WS-*规范,既不是框架, ...
- JavaScrip基础讲座 - 神奇的ProtoType
1. 什么是 prototype prototype 对于 JavaScript 的 意义重大,prototype 不仅仅是一种管理对象继承的机制,更是一种出色的设计思想 在现实生活中,我们常常说, ...
- Android学习笔记(20)————利用ListView制作带竖线的多彩表格
http://blog.csdn.net/conowen/article/details/7421805 /********************************************** ...
- SlideLayout
https://github.com/rey5137/SlideLayout
- [安卓学习]AndroidManifest.xml文件内容详解
一,重要性 AndroidManifest.xml是Android应用程序中最重要的文件之一.它是Android程序的全局配置文件,是每个 android程序中必须的文件.它位于我们开发的应用程序的根 ...
- class、classLoader的getResourceAsStream的区别
1.class.getResourceAsStream() 从源码中可以看出他也是调用ClassLoader的getResourceAsStream() public InputStream getR ...
- PHP泛域名应用
以Windows开发环境 1.windows =>hosts文件 127.0.0.1 asia.t127.0.0.1 *.asia.t127.0.0.1 www.asia.t1 ...
- Mac电脑没有声音,苹果电脑没有声音怎么办
对于使用 Windows 系统电脑的小伙伴来说,可能有很多人会遇到电脑没有声音的问题.苹果 Mac 电脑也会出现没有声音的问题,不过相对较少.这里以我遇到的一个没有声音的问题为例,简单介绍处解决的 ...