美文网首页iOS技术资料
UIDocumentInteractionController和

UIDocumentInteractionController和

作者: 乡水情缘 | 来源:发表于2017-01-06 14:17 被阅读250次

    引言:iOS对浏览文件提供了方便的SDK,让开发者调用实现各自的需求,之前利用UIWebView直接加载本地或者网络路径浏览文件。最近研究了一下UIDocumentInteractionController和QLPreviewController去预览文件,个人感觉各自有各自的优缺点,需要根据具体的业务场景选择适合的方式。
    一、是否可以在线预览刚开始接触时的想法是:是否有在线预览功能,UIDocumentInteractionController和QLPreviewController的显示样式自带分页效果,效果看起来和专业做文档预览的软件,预览效果类似,那不是太好了!然而现实很骨感,查阅了大量资料以及自己测试之后,我可以确定的答案是:不能在线预览!只能加载本地文件。所以采用AFNetworking 先把文件下载到本地然后在显示二、UIDocumentInteractionController使用过UIDocumentInteractionController的小伙伴都知道,虽然它叫控制器,但是它不是真正意义上的控制器而是继承自NSObject的。这也就是为什么要遵循代理方法,告诉UIDocumentInteractionController如何去显示,比如显示在当前控制器,显示的Rect等。
    下载文件的代码:

    - (void)loadFile:(NSString *)url{
        NSURLSessionConfiguration*configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        //http://yz.snnu.edu.cn/uploadfile/2015/0902/20150902091402338.zip
        AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
        NSURL*URL = [NSURL URLWithString:@"http://www.chem.pku.edu.cn/data/upload/5YyX5Lqs5aSn5a2m5YyW5a2m5a0=_6vjZIj.doc"];
        NSURLRequest*request = [NSURLRequest requestWithURL:URL];
        NSURLSessionDownloadTask*downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
            // @property int64_t totalUnitCount;     需要下载文件的总大小
            // @property int64_t completedUnitCount; 当前已经下载的大小
            // 给Progress添加监听 KVO
            NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
            // 回到主队列刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                // 设置进度条的百分比
                self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
            });
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *docDir = [paths objectAtIndex:0];
            NSURL *fileUrl = [NSURL fileURLWithPath:docDir];
            _type = response.suggestedFilename;
            return[fileUrl URLByAppendingPathComponent:[response suggestedFilename]];
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            NSLog(@"下载完成");
        }];
        [downloadTask resume];
    }
    

    第一种 下载完成后采用 UIDocumentInteractionController 打开

    - (void)openFile{
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [paths objectAtIndex:0];
        //打开网络下载的内容  _type 文件的后缀名
        NSString *str = [NSString stringWithFormat:@"%@/%@",docDir,_type];
        //打开本地内容
    //   NSString *str = [[NSBundle mainBundle]pathForResource:@"2012高考北京理科数学试题及答" ofType:@"doc"];
        NSURL *fileUrl = [NSURL fileURLWithPath:str];
    
        NSLog(@"fileUrl-----%@",fileUrl);
        if (fileUrl) {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            
            //检查附件是否存在
            if ([fileManager fileExistsAtPath:str]) {
                UIDocumentInteractionController *documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:fileUrl];
                documentInteractionController.delegate = self;
                //可以重新定义标题的名字
                documentInteractionController.name = @"你大爷";
                [documentInteractionController presentPreviewAnimated:YES];//预览
                //             [documentInteractionController presentOpenInMenuFromRect:CGRectMake(0, 0, 44, 44) inView:self.view animated:YES];//通过第三方APP打开文档
            }
        }
    
    }
    

    要实现的协议方法

    #pragma mark - UIDocumentInteractionController 代理方法
    - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
        //返回的是当前VC,当前VC跳转到UIDocumentInteractionController中
        return self;
    }
    //下面的两个代理方法如果实现的话会在当前页面显示
    //- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
    //    return self.view;
    //}
    //
    //- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
    //    return self.view.bounds;
    //}
    
    1654414-d71067002d9632c1.png

    备注:采用这种方法无法自定义这个导航栏,可能说无法自定义这有点绝对,只是我现在还没有找到好的办法

    第二种方法采用 QLPreviewController
    QLPreviewController的实现和UIDocumentInteractionController类似,但是QLPreviewController是真正的控制器。两者之间虽然实现效果相同,但是还是存在区别的。比如:QLPreviewController可以一起浏览多个文件,而UIDocumentInteractionController一次只能浏览一个文件。使用QLPreviewController之间,需要导入QuickLook.framework,并遵守其数据源和代理方法。实现代码如下:

    #import "ViewController.h"
    #import <QuickLook/QuickLook.h>
    @interface ViewController ()<QLPreviewControllerDataSource,QLPreviewControllerDelegate>
    @end
    @implementation ViewController
    - (void)viewDidLoad { [super viewDidLoad]; //控制当前控制器对应的导航条显示的内容 self.navigationItem.title=@"预览"; 
    NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"iOS开发指南.pdf" ofType:nil]; NSURL *url = [NSURL fileURLWithPath:urlStr]; self.fileUrl = url;
     if ([QLPreviewController canPreviewItem:(id<QLPreviewItem>)url]) { 
    QLPreviewController *qlVc = [[QLPreviewController alloc] init]; 
    qlVc.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64); 
    qlVc.delegate = self;
     qlVc.dataSource = self; qlVc.navigationController.navigationBar.userInteractionEnabled = YES;
     qlVc.view.userInteractionEnabled = YES;
    //如何在当前页面展示的时候 
    //[self.view addSubview:qlVc.view];
     [self presentViewController:qlVc animated:YES completion:nil];
     }}
    #pragma mark - QLPreviewController 代理方法
    -(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
     return 1;
    }
    - (id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{ 
    return self.fileUrl;
    }
    

    备注:采用这种方法是可以自定义导航啦

    1654414-88a99bbbde8d01e7.png

    相关文章

      网友评论

        本文标题:UIDocumentInteractionController和

        本文链接:https://www.haomeiwen.com/subject/nnlgvttx.html