特记录下达成的进程,本身完毕文件下载使用的是AFNetworking

前不久做了个办公系统项目,须要开展落实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];//开始下载 要不然不会进行下载的

}

自我已毕文件下载使用的是AFNetworking,具体完结代码如下:

二.文本存储路径

下载地址不可用,请使用实际地址.
为了有利于,自个儿把下载下来的文件直接保存在了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 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];//初阶下载 要不然不会进展下载的

}

三.预览打开文件

开辟预览下载成功的文书的不二法门如下:

/**
 打开文件

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

二.文书存储路径

下载地址不可用,请使用实际地址.
为了便利,本身把下载下来的文书一向保存在了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

//必须落成的代办方法
预览窗口以方式窗口的款型体现,因而要求在该方法中回到1个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);

}

效益图如下

永利网上娱乐 1

QQ20170227-191541@2x.png

QuickLook打开文档的demo如下:

#import “ViewController.h”

#import

@interface ViewController ()

@property (nonatomic,strong) QLPreviewController *previewVC;

@end

@implementation ViewController

– (void)viewDidLoad {

[super viewDidLoad];

}

-(void)touchesBegan:(NSSet *)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 )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]];

作者:Newquine

链接:http://www.jianshu.com/p/5dcede89d85f

來源:简书

小说权归作者全体。商业转载请联系我拿到授权,非商业转发请注解出处。

相关文章