iOS打开本地和网络上的word、ppt、excel、text等文件

iOS开发过程中可能需要预览一些文件,这些文件的格式可能有word、ppt、excel等文件格式。那么系统提供两个类去预览这些文件,这两个类分别为QLPreviewController和UIDocumentInteractionController。

一、先看QLPreviewController怎么用

  1.导入头文件  import < QuickLook/QuickLook.h >

  2.创建一个继承QuickLookViewController继承UIViewController

  3.遵守协议< QLPreviewControllerDataSource, QLPreviewControllerDelegate >

  1. .h文件中的代码
  2. # import < UIKit/UIKit.h >
  3. # import < QuickLook/QuickLook.h >
  4.  
  5. @interface QuickLookViewController : UIViewController < QLPreviewControllerDataSource,
  6. QLPreviewControllerDelegate >
  7. @property (nonatomic,strong) QLPreviewController *previewController;
  8. @property (nonatomic,retain)NSURL *fileURL;
  9.  
  10. @end
  1. .m文件中的代码:
  2. # import “QuickLookViewController.h”
  3.  
  4. @interface QuickLookViewController ()
  5.  
  6. @end
  7.  
  8. @implementation QuickLookViewController
  9. @synthesize previewController = _previewController;
  10.  
  11. (void)viewDidLoad {
  12. [super viewDidLoad];
  13. self.view.backgroundColor = [UIColor whiteColor];
  14. self.title = @”附件预览”;
  15. _previewController = [[QLPreviewController alloc] init];
  16. _previewController.dataSource = self;
  17. _previewController.delegate = self;
  18.  
  19. _previewController.view.frame = CGRectMake(, , self.view.frame.size.width , self.view.frame.size.height);
  20. _previewController.currentPreviewItemIndex = ;
  21. // [self addChildViewController:_previewController];
  22. [self.view addSubview:_previewController.view];
  23. [_previewController reloadData];
  24.  
  25. }
  26. - (id ) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index{
  27. return self.fileURL;
  28. }
  29. - (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
  30. return ;
  31. }
  32. @end

这样我们就完成了这个QuickLookViewController,使用:

  1. NSString *filePath = [[NSBundle mainBundle] pathForResource:@”Reader ofType:@”pdf”];
  2. NSURL *URL = [NSURL fileURLWithPath:filePath];
  3. QuickLookViewController *quickLookVC = [[QuickLookViewController alloc]init];
  4. quickLookVC.fileURL = URL;//本地图片的url
  5. [self.navigationController pushViewController:quickLookVC animated:YES];

二、再看UIDocumentInteractionController 
  1.建立一个DocumentInteractionViewController,继承UIViewController

  2.遵守代理UIDocumentInteractionControllerDelegate。 

  1. .h里面的代码
  2. # import < UIKit/UIKit.h >
  3.  
  4. @interface DocumentInteractionViewController : UIViewController< UIDocumentInteractionControllerDelegate,UIAlertViewDelegate >
  5. @property(nonatomic,strong) UIDocumentInteractionController *documentInteractionController;
  6. - (void)openFileWithURL:(NSURL *)URL;
  7. @end
  1. .m里面的代码
  2. # import “DocumentInteractionViewController.h”
  3.  
  4. @interface DocumentInteractionViewController ()
  5. {
  6. NSURL *_fileURL;
  7. BOOL _isPreview;
  8. BOOL _isOpenInMenu;
  9. }
  10. @end
  11.  
  12. @implementation DocumentInteractionViewController
  13.  
  14. (void)viewDidLoad {
  15. [super viewDidLoad];
  16. self.view.backgroundColor = [UIColor whiteColor];
  17.  
  18. self.navigationController.navigationBarHidden = YES;
  19.  
  20. }
  21. - (void)openFileWithURL:(NSURL *)URL
  22. {
  23. NSLog(@”now open %@”,URL);
  24. if (URL) {
  25. _fileURL = URL;
  26. _isPreview = NO;
  27. _isOpenInMenu = NO;
  28. // Initialize Document Interaction Controller
  29. self.documentInteractionController = [UIDocumentInteractionController
  30. interactionControllerWithURL:URL];
  31. // Configure Document Interaction Controller
  32. self.documentInteractionController.delegate = self;
  33. // Preview File
  34. [self.documentInteractionController presentPreviewAnimated:YES];
  35.  
  36. [NSTimer scheduledTimerWithTimeInterval: target:self selector:@selector(checkPreview) userInfo:nil repeats:NO];
  37. }
  38. }
  39.  
  40. (void)checkPreview
  41. {
  42. if(_isPreview == NO)
  43. {
  44. if (_fileURL) {
  45. // Initialize Document Interaction Controller
  46. self.documentInteractionController = [UIDocumentInteractionController
  47. interactionControllerWithURL:_fileURL];
  48. // Configure Document Interaction Controller
  49. self.documentInteractionController.delegate = self;
  50. // Present Open In Menu
  51. [self.documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
  52.  
  53. [NSTimer scheduledTimerWithTimeInterval: target:self selector:@selector(checkOpenInMenu) userInfo:nil repeats:NO];
  54. }
  55. }
  56. }
  57.  
  58. (void)checkOpenInMenu{
  59. if(_isOpenInMenu == NO)
  60. {
  61. [self showWarning];
  62. [[UIApplication sharedApplication]openURL:_fileURL];
  63. }
  64. }
  65.  
  66. (void)showWarning{
  67. NSString *fileType = [[_fileURL.absoluteString componentsSeparatedByString:@”.”]lastObject];
  68.  
  69. UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@”出错提示” message:[NSString stringWithFormat:@”不支持%@格式,请下载相关播放器打开”,fileType] delegate:self cancelButtonTitle:@”确定” otherButtonTitles:nil];
  70. [alert show];
  71.  
  72. }
  73.  
  74. (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  75. [self.navigationController popViewControllerAnimated:YES];
  76. }
  77. (UIViewController )documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController )controller{
  78. return self;
  79. }
  80. // Preview presented/dismissed on document. Use to set up any HI underneath.
  81. - (void)documentInteractionControllerWillBeginPreview:(UIDocumentInteractionController *)controller{
  82. controller.name = @”附件预览”;
  83. NSLog(@”willBeginPreview”);
  84. _isPreview = YES;
  85. }
  86.  
  87. (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller{
  88. NSLog(@”didEndPreview”);
  89. [self.navigationController popViewControllerAnimated:YES];
  90. }
  91. // Options menu presented/dismissed on document. Use to set up any HI underneath.
  92. - (void)documentInteractionControllerWillPresentOptionsMenu:(UIDocumentInteractionController *)controller{
  93. NSLog(@”willPresentOptionsMenu”);
  94. }
  95.  
  96. (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller{
  97. NSLog(@”didDismissOptionsMenu”);
  98. }
  99. // Open in menu presented/dismissed on document. Use to set up any HI underneath.
  100. - (void)documentInteractionControllerWillPresentOpenInMenu:(UIDocumentInteractionController *)controller{
  101. NSLog(@”willPresentOpenInMenu”);
  102. _isOpenInMenu = YES;
  103. }
  104. - (void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller{
  105. NSLog(@”didDismissOpenInMenu”);
  106. [self.navigationController popViewControllerAnimated:YES];
  107. }
  108. @end
  109.  
  110. 这样我们就完成了这个DocumentInteractionViewController,再来看用的时候怎么写:
  111. NSString *filePath = [[NSBundle mainBundle] pathForResource:@”Reader ofType:@”pdf”];
  112. NSURL *URL = [NSURL fileURLWithPath:filePath];
  113.  
  114. DocumentInteractionViewController *documentVC = [[DocumentInteractionViewController alloc]init];
  115. [documentVC openFileWithURL:URL]; //本地文件的URL
  116. [self.navigationController pushViewController:documentVC animated:YES];

上面讲的都是打开的本地的文件,那么我如果要预览一个网页上的资源呢?类似这样的URL http://weixintest.ihk.cn/ihkwx_upload/1.pdf ,怎么办? 
理论是这样的,第一次预览,我们要下载到本地,然后打开这个资源,那么第n(n>1)次打开就从本地找到下载的这个资源直接打开就可以了。 
那么我们要在我们的vc里面写一个UIWebView了。比如我们的vc就是OpenRemoteFileViewController,那么来看具体的代码实现

  1. .h文件里面的代码
  2. # import < UIKit/UIKit.h>
  3. #import < QuickLook/QuickLook.h>
  4.  
  5. @interface OpenRemoteFileViewController : UIViewController
  6. @property (nonatomic, retain)NSString *fileURLString;
  7. @end
  1. .m文件里面的代码
  2.  
  3. #import “OpenRemoteFileViewController.h”
  4. @interface OpenRemoteFileViewController () < UIWebViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate >{
  5. UIWebView *openFileWebView;
  6.  
  7. }
  8. @property (nonatomic,strong)NSURL *fileURL;
  9.  
  10. @end
  11.  
  12. @implementation OpenRemoteFileViewController
  13. -(void)openPDF:(UIButton *)sender{
  14. openFileWebView = [[UIWebView alloc]initWithFrame:CGRectMake(, , self.view.frame.size.width, self.view.frame.size.height)];
  15. openFileWebView.delegate = self;
  16. [openFileWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.fileURLString]]];
  17. }
  18. - (void)viewDidLoad {
  19. [super viewDidLoad];
  20.  
  21. self.view.backgroundColor = [UIColor whiteColor];
  22. UIButton *centerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  23. centerBtn.backgroundColor = [UIColor orangeColor];
  24. centerBtn.frame = CGRectMake(, , , );
  25. centerBtn.center = self.view.center;
  26. [centerBtn addTarget:self action:@selector(openPDF:) forControlEvents:UIControlEventTouchUpInside];
  27. [centerBtn setTitle:@"打开一个远程PDF" forState:UIControlStateNormal];
  28. [self.view addSubview:centerBtn];
  29. }
  30. - (BOOL)webView:(UIWebView )webView shouldStartLoadWithRequest:(NSURLRequest )request navigationType:(UIWebViewNavigationType)navigationType
  31. {
  32. return YES;
  33. }
  34. #pragma mark - Web代理
  35. - (void)webViewDidFinishLoad:(UIWebView *)webView
  36. {
  37. NSURL *targetURL = [NSURL URLWithString:self.fileURLString];
  38.  
  39. NSString *docPath = [self documentsDirectoryPath];
  40. NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docPath, [targetURL lastPathComponent]];
  41. NSFileManager *fileManager = [NSFileManager defaultManager];
  42. BOOL hasDownLoad= [fileManager fileExistsAtPath:pathToDownloadTo];
  43. if (hasDownLoad) {
  44. self.fileURL = [NSURL fileURLWithPath:pathToDownloadTo];
  45. QLPreviewController *qlVC = [[QLPreviewController alloc]init];
  46. qlVC.delegate = self;
  47. qlVC.dataSource = self;
  48. [self.navigationController pushViewController:qlVC animated:YES];
  49. //
  50. }
  51. else {
  52. NSURL *targetURL = [NSURL URLWithString:self.fileURLString];
  53.  
  54. NSData *fileData = [[NSData alloc] initWithContentsOfURL:targetURL];
  55. // Get the path to the App's Documents directory
  56. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  57. NSString *documentsDirectory = [paths objectAtIndex:]; // Get documents folder
  58. [fileData writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, [targetURL lastPathComponent]] atomically:YES];
  59. NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
  60. [openFileWebView loadRequest:request];
  61. }
  62.  
  63. NSLog(@"webViewDidFinishLoad");
  64. }
  65.  
  66. (void)webView:(UIWebView )webView didFailLoadWithError:(NSError )error
  67. {
  68. NSLog(@”didFailLoadWithError”);
  69. }
  70.  
  71. (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
  72. return ;
  73. }
  74.  
  75. (id )previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
  76. return self.fileURL;
  77. }
  78.  
  79. (void)previewControllerWillDismiss:(QLPreviewController *)controller {
  80. NSLog(@”previewControllerWillDismiss”);
  81. }
  82.  
  83. (void)previewControllerDidDismiss:(QLPreviewController *)controller {
  84. NSLog(@”previewControllerDidDismiss”);
  85. }
  86.  
  87. (BOOL)previewController:(QLPreviewController )controller shouldOpenURL:(NSURL )url forPreviewItem:(id )item{
  88. return YES;
  89. }
  90.  
  91. (CGRect)previewController:(QLPreviewController )controller frameForPreviewItem:(id )item inSourceView:(UIView __nullable * __nonnull)view{
  92. return CGRectZero;
  93. }
  94.  
  95. (NSString *)documentsDirectoryPath {
  96. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  97. NSString *documentsDirectoryPath = [paths objectAtIndex:];
  98. return documentsDirectoryPath;
  99. }
  100. @end

使用:

  1. OpenRemoteFileViewController *openRemoteFileVC =[[OpenRemoteFileViewController alloc]init];
  2. openRemoteFileVC.fileURLString = @”http://weixintest.ihk.cn/ihkwx_upload/1.pdf“;//网络资源URL
  3. [self.navigationController pushViewController:openRemoteFileVC animated:YES]; 

文章最后提供demo地址:https://github.com/zhengwenming/OpenFile

第五十六篇、OC打开本地和网络上的word、ppt、excel、text等文件的更多相关文章

  1. 第五十六篇:webpack的loader(四) -打包js中的高级语法

    好家伙, 1.打包处理js文件中的高级语法 webpack只能打包处理一部分高级的JavaScript 语法.对于那些webpack无法处理的高级js 语法,需要借 助于 babel-loader 进 ...

  2. 《手把手教你》系列技巧篇(五十六)-java+ selenium自动化测试-下载文件-上篇(详细教程)

    1.简介 前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件.因此宏哥就接着讲解和分享一下:自动化测试下载文件.可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就 ...

  3. 【Visual C++】游戏开发五十六 浅墨DirectX教程二十三 打造游戏GUI界面(一)

    本系列文章由zhmxy555(毛星云)编写,转载请注明出处. 文章链接:http://blog.csdn.net/poem_qianmo/article/details/16384009 作者:毛星云 ...

  4. 跟我学SpringCloud | 第十六篇:微服务利剑之APM平台(二)Pinpoint

    目录 SpringCloud系列教程 | 第十六篇:微服务利剑之APM平台(二)Pinpoint 1. Pinpoint概述 2. Pinpoint主要特性 3. Pinpoint优势 4. Pinp ...

  5. Egret入门学习日记 --- 第十六篇(书中 6.10~7.3节 内容)

    第十六篇(书中 6.10~7.3节 内容) 昨天搞定了6.9节,今天就从6.10节开始. 其实这个蛮简单的. 这是程序员模式. 这是设计师模式. 至此,6.10节 完毕. 开始 6.11节. 有点没营 ...

  6. Python之路【第十六篇】:Django【基础篇】

    Python之路[第十六篇]:Django[基础篇]   Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了O ...

  7. 解剖SQLSERVER 第十六篇 OrcaMDF RawDatabase --MDF文件的瑞士军刀(译)

    解剖SQLSERVER 第十六篇 OrcaMDF RawDatabase --MDF文件的瑞士军刀(译) http://improve.dk/orcamdf-rawdatabase-a-swiss-a ...

  8. 第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy分布式爬虫要点

    第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy分布式爬虫要点 1.分布式爬虫原理 2.分布式爬虫优点 3.分布式爬虫需要解决的问题

  9. “全栈2019”Java第五十六章:多态与字段详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

随机推荐

  1. cocos2d-x 让精灵按照自己设定的运动轨迹行动

    转自:http://blog.csdn.net/ufolr/article/details/7447773 在cocos2d中,系统提供了CCMove.CCJump.CCBezier(贝塞尔曲线)等让 ...

  2. javascript keycode大全【转载】

    keycode    8 = BackSpace BackSpace keycode    9 = Tab Tabkeycode   12 = Clearkeycode   13 = Enterkey ...

  3. WCF与WebService之间的异同

    下面我们来详细讨论一下二者的区别.Web Service和WCF的到底有什么区别. 1,Web Service:严格来说是行业标准,也就是Web Service 规范,也称作WS-*规范,既不是框架, ...

  4. JavaScrip基础讲座 - 神奇的ProtoType

    1. 什么是 prototype  prototype 对于 JavaScript 的 意义重大,prototype 不仅仅是一种管理对象继承的机制,更是一种出色的设计思想 在现实生活中,我们常常说, ...

  5. Android学习笔记(20)————利用ListView制作带竖线的多彩表格

    http://blog.csdn.net/conowen/article/details/7421805 /********************************************** ...

  6. SlideLayout

    https://github.com/rey5137/SlideLayout

  7. [安卓学习]AndroidManifest.xml文件内容详解

    一,重要性 AndroidManifest.xml是Android应用程序中最重要的文件之一.它是Android程序的全局配置文件,是每个 android程序中必须的文件.它位于我们开发的应用程序的根 ...

  8. class、classLoader的getResourceAsStream的区别

    1.class.getResourceAsStream() 从源码中可以看出他也是调用ClassLoader的getResourceAsStream() public InputStream getR ...

  9. PHP泛域名应用

    以Windows开发环境 1.windows =>hosts文件 127.0.0.1    asia.t127.0.0.1    *.asia.t127.0.0.1    www.asia.t1 ...

  10. Mac电脑没有声音,苹果电脑没有声音怎么办

      对于使用 Windows 系统电脑的小伙伴来说,可能有很多人会遇到电脑没有声音的问题.苹果 Mac 电脑也会出现没有声音的问题,不过相对较少.这里以我遇到的一个没有声音的问题为例,简单介绍处解决的 ...