iOS系统方法解读20

iOS开发-下载word/pdf/pages/txt等文件并预览

2017-02-27  本文已影响5052人  Newquine

最近做了个办公系统项目,需要进行实现word文档下载预览功能,以前没有做过相关东西,特记录下实现的过程:

一.实现文件下载

本人实现文件下载使用的是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];//开始下载 要不然不会进行下载的

}

二.文件存储路径

下载地址不可用,请使用实际地址. 为了方便,本人把下载下来的文件直接保存在了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];
        
    }

三.预览打开文件

打开预览下载成功的文件的方法如下:

/**
 打开文件

 @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!!!)

上一篇下一篇

猜你喜欢

热点阅读