iOS文档查看-UIwebview和UIDocumentInte

2018-06-05  本文已影响0人  赑屃王者

一、使用UIwebview浏览文档

1.将文档路径转换为URL

NSURL *documentPathUrl = [NSURL fileURLWithPath:filePath];

2.获取指定URL的MIMEType类型

- (NSString *)mimeType:(NSURL *)url
{
    //1NSURLRequest
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //2NSURLConnection
    
    //3 在NSURLResponse里,服务器告诉浏览器用什么方式打开文件。
    
    //使用同步方法后去MIMEType
    NSURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    return response.MIMEType;
}

3.显示文档

// 通过路径读取文档数据  
     NSData *data = [NSData dataWithContentsOfURL:self.documentPathUrl];
// 将数据传给WebView显示,并且告知文档类型、编码格式 self.url文档请求的URL
    [_webView loadData:data MIMEType:[self mimeType:self.documentPathUrl] textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:self.url]];

二、使用UIDocumentInteractionController

1.声明一个全局变量

@property (nonatomic, strong) UIDocumentInteractionController *documentController;

2.遵循UIDocumentInteractionControllerDelegate代理

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
    return self.view.frame;
}

3.打开的本地文件

_documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
_documentController.delegate = self;// 代理
 _documentController.name = _fileName;// 文件名

4.打开预览
直接打开预览界面[图片上传中...(屏幕快照 2018-06-05 下午5.40.22.png-9fa213-1528191656840-0)]

[_documentController presentPreviewAnimated:YES];

有查看的文件分享弹窗

[_documentController presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];

没有查看的文件分享弹窗

[_documentController presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];
上一篇下一篇

猜你喜欢

热点阅读