一.实现文件下载
本人实现文件下载使用的是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
@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
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
网友评论