App 開發中難免要開啟各種格式的檔案——Excel、Word、PDF、圖片,甚至想呼叫第三方 App 來開。iOS 提供了兩套現成方案:UIDocumentInteractionController 負責「用其他 App 打開/分享」,Quick Look 負責「在 App 內直接預覽」。
首先讓你的類別遵循 UIDocumentInteractionControllerDelegate,宣告一個 retain 性質的屬性(務必持有,否則物件會立刻被釋放而導致功能失效),然後建立並設定 URL。
@property(nonatomic, retain) UIDocumentInteractionController *docController;
- (void)open {
NSString *fileName = [self.listDic objectForKey:@"fileName"];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:@"Documents/%@", fileName]];
_docController = [UIDocumentInteractionController interactionControllerWithURL:
[NSURL fileURLWithPath:path]];
_docController.delegate = self;
// 方案 A:直接顯示預覽
// [_docController presentPreviewAnimated:YES];
// 方案 B:顯示「包含預覽」的完整選單
CGRect navRect = self.navigationController.navigationBar.frame;
navRect.size = CGSizeMake(1500.0f, 40.0f);
[_docController presentOptionsMenuFromRect:navRect
inView:self.view
animated:YES];
// 方案 C:顯示「不含預覽」的選單
// [_docController presentOpenInMenuFromRect:navRect
// inView:self.view
// animated:YES];
}
對應的代理方法:
- (UIViewController *)documentInteractionControllerViewControllerForPreview:
(UIDocumentInteractionController *)controller {
return self;
}
- (UIView *)documentInteractionControllerViewForPreview:
(UIDocumentInteractionController *)controller {
return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:
(UIDocumentInteractionController *)controller {
return self.view.frame;
}
1. 一定要 retain。這個物件若宣告為 assign 或只在區域變數中持有,方法執行完就被回收,後續選單點擊會直接崩潰。
2. presentOptionsMenu 有已知的崩潰風險。呼叫 presentOptionsMenuFromRect:inView:animated: 時,系統會觸發內建的日誌輸出,把「unknown activity items supplied」加上大量二進位內容傾印到 console。資料量大時不僅會拖慢執行,嚴重者可能導致 App 崩潰甚至裝置當機。遇到這種情況,建議改用方案 C 的 presentOpenInMenu,或乾脆換用下面的 Quick Look。
步驟一:加入 QuickLook.framework。
步驟二:在需要的控制器引入 <QuickLook/QuickLook.h>,並遵循 QLPreviewControllerDataSource 與 QLPreviewControllerDelegate。
步驟三:建立並呈現預覽控制器。
- (void)open {
QLPreviewController *preview = [[QLPreviewController alloc] init];
preview.delegate = self;
preview.dataSource = self;
[preview setCurrentPreviewItemIndex:0];
[self presentViewController:preview animated:YES completion:nil];
}
步驟四:實作資料來源方法。
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
return 1;
}
- (id<QLPreviewItem>)previewController:(QLPreviewController *)controller
previewItemAtIndex:(NSInteger)index {
NSString *fileName = [self.listDic objectForKey:@"fileName"];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:@"Documents/%@", fileName]];
return [NSURL fileURLWithPath:path];
}
只是想「在 App 內看一眼內容」,用 Quick Look:穩定、可控、無需離開 App。想「把檔案丟給其他 App 處理或分享」,才用 UIDocumentInteractionController,並記得優先選擇不含預覽的 presentOpenInMenu 版本以避開日誌傾印問題。