那么其落到实处格局有哪些呢,接下去我们在上一篇的根基之上来分析一下在线文件的预览

偶然根绝项目开发的急需,大家要求预览本地的公文(word、Excel、pdf等)。
例如:

在上一篇http://www.jianshu.com/p/00e76c936121
中,大家精通了iOS本地文件预览达成的两种艺术,接下去我们在上一篇的基础之上来分析一下在线文件的预览。

不久前做了个办公室系统项目,必要展开落到实处word文档下载预览效用,从前从未做过有关东西,特记录下完结的历程:

呈现效果

一、webView###\

加载方法:

self.fileURLString = @“文件url地址”;  
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]]];  

代办方法:

- (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");       
}  

- (NSString *)documentsDirectoryPath {  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];  
    return documentsDirectoryPath;  
}  

咱们根绝一个没错的地址,就能打开一个文本了

ca88亚洲城网站 1

在线.doc

ca88亚洲城网站,一.贯彻公文下载

本身完毕公文下载使用的是AFNetworking,具体完成代码如下:

/**
 下载文件

 @param docPath 文件路径
 @param fileName 文件名
 */
-(void)downloadDocxWithDocPath:(NSString *)docPath fileName:(NSString *)fileName {
    [MBProgressHUD showMessage:@"正在下载文件" toView:self.view];
    NSString *urlString = @"http://66.6.66.111:8888/UploadFile/";

    urlString = [urlString stringByAppendingString:fileName];

    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NKLog(@"%lld   %lld",downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);

    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *path = [docPath stringByAppendingPathComponent:fileName];
        NKLog(@"文件路径===%@",path);
        return [NSURL fileURLWithPath:path];//这里返回的是文件下载到哪里的路径 要注意的是必须是携带协议file://
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showSuccess:@"下载完成,正在打开" toView:self.view];
//        if (error) {
//            
//        }else {
            NSString *name = [filePath path];
            NKLog(@"下载完成文件路径===%@",name);
            [self openDocxWithPath:name];
//        }
    }];
    [task resume];//开始下载 要不然不会进行下载的

}

那就是说其促成方式有哪些吗?
iOS的当地文件预览首要有以下二种格局。

二、QuickLook###\

导入#import <QuickLook/QuickLook.h>
实现QLPreviewControllerDataSource,QLPreviewControllerDelegate
其实际贯彻格局如下:

QLPreviewController *qlController = [[QLPreviewController alloc]init];
qlController.delegate = self;
qlController.dataSource = self;
[qlController setCurrentPreviewItemIndex:0];
[self presentViewController:qlController animated:YES completion:nil];


- (id <QLPreviewItem>)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 <QLPreviewItem>)item{  
    return YES;  
}  

- (CGRect)previewController:(QLPreviewController *)controller frameForPreviewItem:(id <QLPreviewItem>)item inSourceView:(UIView * __nullable * __nonnull)view{  
    return CGRectZero;  
}  

二.文件存储路径

下载地址不可用,请使用实际地址.
为了便于,本人把下载下来的文本一贯保存在了Documents文件夹下,代码如下:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths lastObject];

    NKLog(@"app_home_doc: %@",documentsDirectory);

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:docPath]; //docPath为文件名

    if ([fileManager fileExistsAtPath:filePath]) {
        //文件已经存在,直接打开
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

        [alertController addAction:cancelAction];

        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self openDocxWithPath:filePath];
        }]];

        [alertController.actions setValue:[UIColor colorWithHexString:@"3998ef"] forKey:@"_titleTextColor"];
        [self presentViewController:alertController animated:YES completion:nil];

    }else {
        //文件不存在,要下载
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否下载并打开打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

        [alertController addAction:cancelAction];

        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self downloadDocxWithDocPath:documentsDirectory fileName:docPath];
        }]];

        [alertController.actions setValue:[UIColor colorWithHexString:@"3998ef"] forKey:@"_titleTextColor"];
        [self presentViewController:alertController animated:YES completion:nil];

    }

一、UIDocumentInteractionController###\

     //本地文件的绝对路径
     NSString *path = [[NSBundle mainBundle] pathForResource:@"接口文档3.30号" ofType:@"docx"];
     NSURL *url = [NSURL fileURLWithPath:path];

     UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL:url];
     interactionController.delegate = self;

     //预览有其他软件打开按钮
     [interactionController presentPreviewAnimated:NO];

     CGRect navRect = self.navigationController.navigationBar.frame;
     navRect.size =CGSizeMake(1500.0f,40.0f);

     //直接显示包含预览的菜单项
     [interactionController presentOpenInMenuFromRect:navRect inView:self.view animated:YES];

俺们设置了interactionController.delegate =
self;就要贯彻UIDocumentInteractionControllerDelegate中其对应的代理方法

-(UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}
-(UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
    return self.view;
}
-(CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
    return  self.view.frame;
}

command+R,大家就能看到已毕效益了

三.预览打开文件

打开预览下载成功的文书的法子如下:

/**
 打开文件

 @param filePath 文件路径
 */
-(void)openDocxWithPath:(NSString *)filePath {

    UIDocumentInteractionController *doc= [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
    doc.delegate = self;
    [doc presentPreviewAnimated:YES];
}

自身使用的是UIDocumentInteractionController,仍可以使用QuickLook或者webView打开文件,后边会贴小demo.设置UIDocumentInteractionController代理,添加代理方法.

#pragma mark - UIDocumentInteractionControllerDelegate
//必须实现的代理方法 预览窗口以模式窗口的形式显示,因此需要在该方法中返回一个view controller ,作为预览窗口的父窗口。如果你不实现该方法,或者在该方法中返回 nil,或者你返回的 view controller 无法呈现模式窗口,则该预览窗口不会显示。

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{

    return self;
}

- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller {

    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {

    return CGRectMake(0, 30, kDeviceWidth, kDeviceHeight);
}

功用图如下

QQ20170227-191541@2x.png

QuickLook打开文档的demo如下:

#import "ViewController.h"
#import <QuickLook/QuickLook.h>

@interface ViewController ()<QLPreviewControllerDataSource>

@property (nonatomic,strong) QLPreviewController *previewVC;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.previewVC = [[QLPreviewController alloc] init];
    self.previewVC.dataSource = self;
    [self presentViewController:self.previewVC animated:YES completion:nil];
}

//实现代理协议
#pragma mark-----------QLPreviewControllerDataSource

//要显示的文件的数量
/*!
 * @abstract Returns the number of items that the preview controller should preview.
 * @param controller The Preview Controller.
 * @result The number of items.
 */
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
    return 3;
}


- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
    //这个是加载的本地的pdf的文件,doc的同理
    NSString *path;
    switch (index) {
        case 0:
        {
            path = [[NSBundle mainBundle] pathForResource:@"testDoc" ofType:@"docx"];
        }
            break;
        case 1:
        {
            path = [[NSBundle mainBundle] pathForResource:@"testDoc" ofType:@"pages"];
        }
            break;

        case 2:
        {
            path = [[NSBundle mainBundle] pathForResource:@"testDoc" ofType:@"pdf"];
        }
            break;


        default:
            break;
    }
    NSURL *url = [NSURL fileURLWithPath:path];
    return url;
}

webView预览文档的方式如下:

    NSString *filePath = @"";//文件存储地址
    NSURL *url = [NSURL fileURLWithPath:filePath];
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight)];
    [webView loadRequest:[NSURLRequest requestWithURL:url]];

就写到那里,有怎么样错误的地点请情侣指正!!!
(若有朋友完成了iOS端可填写Excel表格,跪求Demo!!!)

二、quickLook###\

quickLook也是系统提供的
第一导入#import <QuickLook/QuickLook.h>

        QLPreviewController *qlController = [[QLPreviewController alloc]init];
        qlController.delegate = self;
        qlController.dataSource = self;
        [qlController setCurrentPreviewItemIndex:0];
        [self presentViewController:qlController animated:YES completion:nil];

接下去贯彻QLPreviewControllerDelegate,QLPreviewControllerDataSource中的相关办法:

/*!
 * @abstract Returns the number of items that the preview controller should preview.
 * @param controller The Preview Controller.
 * @result The number of items.
 */
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
    return 1;
}

/*!
 * @abstract Returns the item that the preview controller should preview.
 * @param controller The Preview Controller.
 * @param index The index of the item to preview.
 * @result An item conforming to the QLPreviewItem protocol.
 */
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"接口文档330号" ofType:@"docx"];
    NSURL *url = [NSURL fileURLWithPath:path];
    return url;
}

那样,就能促成公文的预览了

三,UIWebView / WKWebView###\

现以webView为例,来落到实处公文预览,我切实贯彻细节如下:

    _webView.delegate = self;
    _webView.multipleTouchEnabled = YES;
    _webView.scalesPageToFit = YES;
    _webView.scrollView.bounces = NO;
    NSStringEncoding *useEncodeing = nil;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"接口文档330号" ofType:@"docx"];
    NSString *body = [NSString stringWithContentsOfFile:path encoding:(long)useEncodeing error:nil];
    if (body) {

        body =[body stringByReplacingOccurrencesOfString:@"\n" withString:@"<br>"];//替换换行符为HTML换行符

        [_webView loadHTMLString:body baseURL:[NSURL fileURLWithPath:path]];

    }else { //其他文件直接加载请求

        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
        [_webView loadRequest:request];
    }

webView加载达成调用:

- (void)webViewDidFinishLoad:(UIWebView *)webView

{
    //获取加载的h5字符串的body

    NSString *lJs = @"document.documentElement.innerText";//获取当前网页的html

    NSString *currentHTMLBody = [webView stringByEvaluatingJavaScriptFromString:lJs];

    if ([currentHTMLBody isEqualToString:@""]) { //不能预览

        //做一些不能预览的处理操作
    }
    ;
}

相关文章