iOS-打开word、ppt、pdf、execl文档方式

时间:2024-02-29 21:02:28

这里面包括下载和打开文档的操作:需要先导入《AFNetworking》的框架

 

第一步:创建一个显示文档的view:ReadViewController

(1).h的代码如下:

@interface ReadViewController : UIViewController
-(void)loadOfficeData:(NSString *)officePath;
@end

 (2).m的代码如下:

@interface ReadViewController ()
{
    UIWebView * _dataView;
    NSString* _urlStr;
}
@end

@implementation ReadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)])
    {
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
    }
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
    {    self.edgesForExtendedLayout = UIRectEdgeNone;   }
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
}

- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}
//仍然下载上面的。m里面

-(void)loadOfficeData:(NSString *)officePath{
    _urlStr=officePath;
    
    if (!_dataView) {
        _dataView=[[UIWebView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height)];
        [self.view addSubview:_dataView];
        
    }
    _dataView.autoresizingMask=UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    
    NSURL *url = [[NSURL alloc] initWithString:_urlStr];
    _dataView.scalesPageToFit = YES;
    NSURLRequest *requestDoc = [NSURLRequest requestWithURL:url];
    [_dataView loadRequest:requestDoc];
    
    
}

 

 

第二步:创建一个下载和打开文档的工具类:YZFileDownloadAndReadTool

(1)YZFileDownloadAndReadTool.h的代码如下:

@interface YZFileDownloadAndReadTool : NSObject

/* 打开文档 */
- (void)openDocument:(NSString *)documentPath;

//设置单利
+ (YZFileDownloadAndReadTool *)shareManager;

@end

 (2)YZFileDownloadAndReadTool.m的代码如下:

#import "YZFileDownloadAndReadTool.h"

#import "ReaderViewController.h"
#import "AFNetworking.h"
#import "ReadViewController.h"

#define GetFileInAppData(file) [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",file]]

@interface YZFileDownloadAndReadTool ()<ReaderViewControllerDelegate>

@end

@implementation YZFileDownloadAndReadTool

+ (YZFileDownloadAndReadTool *)shareManager {
    static YZFileDownloadAndReadTool *shareManagerInstance = nil;
    static dispatch_once_t predicate; dispatch_once(&predicate, ^{
        shareManagerInstance = [[self alloc] init];
    });
    return shareManagerInstance;
}

/**
 *  @author Jakey
 *
 *  @brief  下载文件
 *
 *  @param paramDic   附加post参数
 *  @param requestURL 请求地址
 *  @param savedPath  保存 在磁盘的位置
 *  @param success    下载成功回调
 *  @param failure    下载失败回调
 *  @param progress   实时下载进度回调
 */
- (void)downloadFileWithOption:(NSDictionary *)paramDic
                 withInferface:(NSString*)requestURL
                     savedPath:(NSString*)savedPath
               downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
               downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                      progress:(void (^)(float progress))progress

{
    
    //沙盒路径    //NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxx.zip"];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request =[serializer requestWithMethod:@"POST" URLString:requestURL parameters:nil error:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float p = (float)totalBytesRead / totalBytesExpectedToRead;
        progress(p);
        NSLog(@"download:%f", (float)totalBytesRead / totalBytesExpectedToRead);
        
    }];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation,responseObject);
        NSLog(@"下载成功");
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        success(operation,error);
        
        NSLog(@"下载失败");
        
    }];
    
    [operation start];
}

- (void)downloadDocumentOperation:(NSString *)fileName {
    NSString *filePath = GetFileInAppData(fileName);
    NSString *tempFileName = [NSString stringWithFormat:@"%@.bak",fileName];
    NSString *tempFilePath = GetFileInAppData(tempFileName);
    
    NSLog(@"----savePath----%@", filePath);
    
#warning url 需要修改
    
    [self downloadFileWithOption:nil
                   withInferface:@"http://223.202.51.70/FileServer/DownloadFile/17adc036-24ac-4df8-8a49-90c312c0f300.pdf"
                       savedPath:filePath
                 downloadSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                     [[NSFileManager defaultManager] moveItemAtPath:tempFilePath toPath:filePath error:nil];
//                     [self openDocument:filePath];
                     [self openHadDownloadDocument:fileName];
                 } downloadFailure:^(AFHTTPRequestOperation *operation, NSError *error) {
                     
                 } progress:^(float progress) {
                     
                 }];
}

/* 打开文档 */
- (void)openDocument:(NSString *)documentPath{
 
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    NSString *filePath = GetFileInAppData(documentPath);
    NSString *documentName = [filePath lastPathComponent];
    
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [self downloadDocumentOperation:documentPath];
        return;
    }
    
        ReadViewController * readView=[[ReadViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:readView];
        [window.rootViewController presentViewController:nav animated:YES completion:nil];
        
        readView.navigationItem.title=documentPath;
        NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        NSString* _urlStr=[NSString stringWithFormat:@"%@/%@",documentsDirectory,[documentPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
        [readView loadOfficeData:_urlStr];
    
}

 

第三步:在需要的点击,倒入 YZFileDownloadAndReadTool.h,接着实现

#pragma mark - 点击界面下载pdf
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

//    YZFileDownloadAndReadTool *tools = [YZFileDownloadAndReadTool shareManager];
//    [tools openDocument:@"01-传感器.pptx"];
    
    [[YZFileDownloadAndReadTool shareManager] openDocument:@"01-传感器.pptx"];
//    [tools openDocument:@"button圆角的设置和边框的设置.docx"];
//    [tools openDocument:@"沃迪康工作计划安排.xlsx"];
//    [tools openDocument:@"ArcGIS for iOS 2.3开发教程-基础版.pdf"];
}