在应用开发中,有时候需要预览文档和视频,使用 UIDocumentInteractionController 来预览文件非常方便,支持的格式比较多,比如 docx、xlsx、pdf、mov、mp4、jpg、png 等等都可以。具体代码如下:

@interfaceViewController()<UIDocumentInteractionControllerDelegate>@property(nonatomic,strong)UIDocumentInteractionController*documentVC;@end@implementationViewController-(void)viewDidLoad{[superviewDidLoad];//Doanyadditionalsetupafterloadingtheview,typicallyfromanib.NSString*path=[[NSBundlemainBundle]pathForResource:@"第7章Mach-O文件格式解析"ofType:@"docx"];NSURL*url=[NSURLfileURLWithPath:path];self.documentVC=[UIDocumentInteractionControllerinteractionControllerWithURL:url];self.documentVC.delegate=self;dispatch_async(dispatch_get_main_queue(),^{BOOLb=[self.documentVCpresentPreviewAnimated:YES];});}#pragmamark代理方法//为快速预览指定控制器-(UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller{NSLog(@"%@",NSStringFromSelector(_cmd));returnself;}//为快速预览指定View-(UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller{NSLog(@"%@",NSStringFromSelector(_cmd));returnself.view;}//为快速预览指定显示范围-(CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller{NSLog(@"%@",NSStringFromSelector(_cmd));//returnself.view.frame;returnCGRectMake(0,0,self.view.frame.size.width,300);}@end

效果如下图,点击 Done 就能回到主界面。


原文地址:https://www.exchen.net/ios-%E6%96%87%E4%BB%B6%E9%A2%84%E8%A7%88-uidocumentinteractioncontroller.html