iOS利用UIDocumentInteractionController和Quick Look開啟或預覽文檔
在App的開發過程中,我們避免不了要開啟軟體中的檔案,例如:Excel檔案,Word檔案,圖片檔案等不同格式的檔案或者想要通過第三方的App來開啟這些檔案,那麼我們就要用到UIDocumentInteractionController和Quick Look來解決這些問題了。
UIDocumentInteractionController的使用方法
UIDocumentInterRactionController使用時的注意事項
Quick Look的使用方法
一、UIDocumentInteractionController的使用方法
- 首先建立一個UIDocumentInteractionController對象,並對該對象初始化一個URL作為檔案路徑
1、首先要遵循UIDocumentInteractionControllerDelegate2、其次是建立一個UIDocumentInteractionController對象@property(nonatomic,retain)UIDocumentInteractionController *docController;3、在方法中進行UIDocumentInteractionController對象的初始化- (void)open{NSString *fileName = [self.listDicobjectForKey:@"fileName"];NSString* path = [NSHomeDirectory()stringByAppendingPathComponent:_docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path]];//為該對象初始化一個載入路徑_docController.delegate =self;//設定代理//直接顯示預覽// [_docController presentPreviewAnimated:YES];CGRect navRect =self.navigationController.navigationBar.frame; navRect.size =CGSizeMake(1500.0f,40.0f);//顯示包含預覽的功能表項目[_docController presentOptionsMenuFromRect:navRectinView:self.viewanimated:YES];//顯示不包含預覽功能表項目//[docController presentOpenInMenuFromRect:navRect inView:self.view animated:YES];}4、代理方法- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{ return self;}- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{ return self.view;}- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{ return self.view.frame;}
二、UIDocumentInterRactionController使用時的注意事項
1、UIDocumentInterRactionController定義的時候一定要是retain類型的,因為必須要對該對象進行持有;
2、當選擇顯示包含預覽的功能表項目
[_docController presentOptionsMenuFromRect:navRectinView:self.viewanimated:YES];時應該注意一點,該方法會觸發該類的內建列印輸出,會將日誌資訊列印出來,從而導致App崩潰嚴重的可能會導致手機死機,現在還未找到解決方案。類似輸出結果如下(此處省略該輸出的後面部分內容,因為太多了):
unknown activity items supplied: ( { "public.jpeg" =
當上述方法確實無法滿足你的要求的時候就可以考慮一下用Quick Look了。
三、Quick Look的使用方法
1、首先要添加QuickLook.FrameWork架構,具體怎麼添加的我就不解釋了。
2、在需要用到的Controller中添加標頭檔#import
- (void)open{ QLPreviewController *myQlPreViewController = [[QLPreviewController alloc]init]; myQlPreViewController.delegate =self; myQlPreViewController.dataSource =self; [myQlPreViewController setCurrentPreviewItemIndex:0]; [self presentViewController:myQlPreViewControlleranimated:YEScompletion:nil];
5、代理方法
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{ return 1;}- (id)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{ NSString *fileName = [self.listDicobjectForKey:@"fileName"]; NSString* path = [NSHomeDirectory()stringByAppendingPathComponent:[NSStringstringWithFormat:@"Documents/%@",fileName]]; return [NSURLfileURLWithPath:path];}