iOS開發(fā)-下載word/pdf/pages/txt等文件并預(yù)覽

一.實現(xiàn)文件下載

本人實現(xiàn)文件下載使用的是AFNetworking,具體實現(xiàn)代碼如下:

/**

下載文件

@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];//這里返回的是文件下載到哪里的路徑 要注意的是必須是攜帶協(xié)議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]) {

//文件已經(jīng)存在,直接打開

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];

}

三.預(yù)覽打開文件

打開預(yù)覽下載成功的文件的方法如下:

/**

打開文件

@param filePath 文件路徑

*/

-(void)openDocxWithPath:(NSString *)filePath {

UIDocumentInteractionController *doc= [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];

doc.delegate = self;

[doc presentPreviewAnimated:YES];

}

本人使用的是UIDocumentInteractionController,還可以使用QuickLook或者webView打開文件,后面會貼小demo.設(shè)置UIDocumentInteractionController代理,添加代理方法.

#pragma mark - UIDocumentInteractionControllerDelegate

//必須實現(xiàn)的代理方法 預(yù)覽窗口以模式窗口的形式顯示,因此需要在該方法中返回一個view controller ,作為預(yù)覽窗口的父窗口。如果你不實現(xiàn)該方法,或者在該方法中返回 nil,或者你返回的 view controller 無法呈現(xiàn)模式窗口,則該預(yù)覽窗口不會顯示。

- (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];

}

//實現(xiàn)代理協(xié)議

#pragma mark-----------QLPreviewControllerDataSource

//要顯示的文件的數(shù)量

/*!

* @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預(yù)覽文檔的方法如下:

NSString *filePath = @"";//文件存儲地址

NSURL *url = [NSURL fileURLWithPath:filePath];

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight)];

[webView loadRequest:[NSURLRequest requestWithURL:url]];

作者:Newquine

鏈接:http://m.itdecent.cn/p/5dcede89d85f

來源:簡書

著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容