UIDocumentInteractionController 是iOS很早就出来的一个功能。但由于平时很少用到,压根就没有听说过它。而我们忽略的缺是一个功能强大的”文档阅读器”。
UIDocumentInteractionController主要由两个功能,一个是文件预览,另一个就是调用iPhoneh里第三方相关的app打开文档(注意这里不是根据url scheme 进行识别,而是苹果的自动识别)
以 pdf 为例 (还查看doc、ppt、docx、pdf、xls格式文件)
声明:
@property(nonatomic,strong) UIDocumentInteractionController *documentController; //文档交互控制器
这个是它的代理<UIDocumentInteractionControllerDelegate>
代理:
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
//注意:此处要求的控制器,必须是它的页面view,已经显示在window之上了
return self.navigationController;
}
以下两种使用方法(button点击方法):
//预览
- (void)previewClick:(UIButton *)btn {
//初始化文档交互
//准备文档的Url
NSURL *url = [[NSBundle mainBundle] URLForResource:@"haha.pdf" withExtension:nil];
self.documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
[self.documentController setDelegate:self];
//当前APP打开 需实现协议方法才可以完成预览功能
[self.documentController presentPreviewAnimated:YES];
}
//第三方打开 手机中安装有可以打开此格式的软件都可以打开
- (void)openClick:(UIButton *)btn {
//初始化文档交互
//准备文档的Url
NSURL *url = [[NSBundle mainBundle] URLForResource:@"haha.pdf" withExtension:nil];
self.documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
[self.documentController setDelegate:self];
[self.documentController presentOpenInMenuFromRect:btn.frame inView:self.view animated:YES];
}