場景:pdf文件通過下載接口存儲到本地后的預(yù)覽和分享.
方案一: UIDocumentinteractionController
使用方法:
1.創(chuàng)建一個UIDocumentInteractionController類的屬性:必須要寫成strong修飾符類型的屬性,原因很簡單,彈出的頁面上操作設(shè)計到別的模塊操作(比如保存到文件App)那么該VC就會被釋放掉,通過強引用的方式解決
@property (nonatomic,strong)UIDocumentInteractionController * document;
2.遵循UIDocumentInteractionControllerDelegate
<UIDocumentInteractionControllerDelegate>
3.document的使用
//沙盒路徑
NSString *newfilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"下載項/%@-%@.pdf",[fileString lastPathComponent],_fileName]];
NSURL *url = [NSURL fileURLWithPath:newfilePath];
//初始化
self-> document = [UIDocumentInteractionController interactionControllerWithURL:url];
self-> document.delegate = self;
//頁面彈出
//用戶預(yù)覽文件
[self->document presentPreviewAnimated:YES];
// 用戶不預(yù)覽文件直接分享
[self.document presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];
//代理(其他代理根據(jù)實際情況添加]
)
- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller{
return self;
}
方案二:UIDocumentPickerViewController
1.使用說明:該方式是手動的選擇文件App中路徑,手動存入
//Mode 選擇UIDocumentPickerModeExportToService為手動存入文件到文件App
UIDocumentPickerViewController *documentPicker =
[[UIDocumentPickerViewController alloc]initWithURLs:@[url] inMode:UIDocumentPickerModeExportToService];
//解決不能全屏顯示
[[UINavigationBar appearance] setTranslucent:NO];;
documentPicker.delegate = self;
[self presentViewController:documentPicker animated:YES completion:nil];
備注:
重點要了解UIDocumentPickerViewController在初始化的時候inMode的四種模式:
UIDocumentPickerModeImport: Import從提供者那里獲得文件并拷貝到我們的host app。最經(jīng)典的應(yīng)用場景是在內(nèi)容創(chuàng)建類應(yīng)用中的使用。例如,像keynote、PowerPoint這樣的演示制作應(yīng)用,希望導入圖片,視頻,以及音頻。它們希望拷貝一份這些數(shù)據(jù)以此保證它們隨時可用。
UIDocumentPickerModeOpen: 和import一樣,open同樣從文件提供者那里獲得數(shù)據(jù)并導入我們的host app,只是不同的是,這些數(shù)據(jù)沒有被拷貝一份至我們的host app,數(shù)據(jù)還在原處。例如,你或許在音樂播放器、視頻播放器,再或者圖像編輯器中使用該方式。
UIDocumentPickerModeExportToService: Export使我們的host app可以保存文件至其它提供者。例如,這些提供者可能是常用的像Dropbox、iCloud Drive這樣的云存儲系統(tǒng)。host app可以通過export保存文件到提供者的存儲空間。在接下來的編輯器例子中,當用戶完成編輯,他們可以導出文件,然后稍后可以在其它app中打開這些文件。
UIDocumentPickerModeMoveToService: 除了host app不會持有一份兒文件的拷貝,其它Moving和export差不多。這或許是最不常用的操作,因為大多數(shù)iOS apps不是為了拋棄它們的數(shù)據(jù)才創(chuàng)建的。
說明:使用import方式示例
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc]
initWithDocumentTypes:@[@"public.image"] inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
2.使用說明:該方式是開放'文件App'對Host App的訪問權(quán)限,默認在文件App中生成一個Host App的文件夾,并且開放Documents文件的訪問
a.plist文件中添加
Application supports iTunes file sharing YES
Supports opening documents in place YES
b.通過代碼將文件添加到沙盒(下載代碼 根據(jù)實際需求實現(xiàn))