#iOS打开本地和网络上的word、ppt、excel、text等文件#
iOS开发过程中可能需要预览一些文件,这些文件的格式可能有word、ppt、excel等文件格式。那么系统提供两个类去预览这些文件,这两个类分别为QLPreviewController和UIDocumentInteractionController。
一、先看QLPreviewController怎么用。
我们要用QLPreviewController,首先要 import < QuickLook/QuickLook.h >,然后创建一个QuickLookViewController继承UIViewController,并且要遵守QuickLookViewController的代理方法 < QLPreviewControllerDataSource,
QLPreviewControllerDelegate >,这个和tableView的用法很相似。下面看代码:
.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(0, 64, self.view.frame.size.width , self.view.frame.size.height);
_previewController.currentPreviewItemIndex = 0;
// [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 1;
}
@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怎么用。
我们还是要建立一个DocumentInteractionViewController,继承UIViewController,并且遵守代理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:1 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:1 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(0, 64, 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(0, 0, 200, 50);
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:0]; // 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 1;
}(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:0];
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
原创博客,不得转载,谢谢。
另外博主维护一个iOS开发技术支持群:479259423,进群必须改名,群名片格式:城市-iOS-名字,例如广州-iOS-文明。