做 IM 的时候大家有没有遇到如何处理朋友发来的文件呢?查找很多资料上都是说可以用 webView 来展示,其实苹果已经为大家准备了一个类QLPreviewController,可以用来预览不同种类的文件。废话不多说,直接上代码。
1、创建一个文件预览控制器
QLPreviewController *plPreVC = [QLPreviewController new];
plPreVC.view.frame = self.view.bounds;
plPreVC.delegate = self;
plPreVC.dataSource = self;
plPreVC.navigationController.navigationBar.userInteractionEnabled = YES;
plPreVC.view.userInteractionEnabled = YES;
[self presentViewController:plPreVC animated:YES completion:nil];
注意:
1>添加 QuickLook 头文件,添加 QuickLook.framework 支持库
#import <QuickLook/QuickLook.h>
2>设置代理
<QLPreviewControllerDelegate, QLPreviewControllerDataSource>
2、完成代理方法
#pragma mark --- QLPreviewController代理方法
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
return 1;
}
/** 返回本地将要读写的文件地址 */
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
/** 获取 cache 文件的地址 */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
NSString *filePath = [cachesDir stringByAppendingPathComponent:@"代码规范.pdf"];
return filePath;
}
具体效果如下: