iOS 文件瀏覽器UIDocumentPickerViewController

最近需要用到文件導(dǎo)入導(dǎo)出功能,導(dǎo)出使用類UIDocumentInteractionController很容易實(shí)現(xiàn),但文件導(dǎo)入?yún)s找了好久都沒(méi)找到符合需求的,本來(lái)找到UIDocumentBrowserViewController,以為可以了,可是并不能滿足需求,可能是我不會(huì)用吧,而且UIDocumentBrowserViewController需要iOS11以上的系統(tǒng)版本才支持,最終看到一篇文章,讓我見(jiàn)到了光明:http://m.itdecent.cn/p/607b96ddc757,使用UIDocumentPickerViewController完美解決問(wèn)題,支持iOS8。

話不多說(shuō),上代碼!!

1、本地文件導(dǎo)出

#pragma mark 導(dǎo)出

- (void)exportFile {

[selfopenDocumentInResourceFolder];

}

- (void)openDocumentInResourceFolder {

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"iOSNotes"ofType:@"pdf"];

_documentController = [UIDocumentInteractionController? interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];

_documentController.delegate = self;

//? ? _documentController.UTI = @"com.adobe.pdf";//

[_documentControllerpresentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];

}

2、導(dǎo)入文件

#pragma mark 導(dǎo)入

- (void)importFile {

[selfpresentDocumentPicker];

}

- (void)presentDocumentPicker {

NSArray*types =@[

@"public.data",

@"com.microsoft.powerpoint.ppt",

@"com.microsoft.word.doc",

@"com.microsoft.excel.xls",

@"com.microsoft.powerpoint.pptx",

@"com.microsoft.word.docx",

@"com.microsoft.excel.xlsx",

@"public.avi",

@"public.3gpp",

@"public.mpeg-4",

@"com.compuserve.gif",

@"public.jpeg",

@"public.png",

@"public.plain-text",

@"com.adobe.pdf"

];// 可以選擇的文件類型

UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeImport];

documentPicker.delegate=self;

documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;

[selfpresentViewController:documentPicker animated:YEScompletion:nil];

}

- (void)documentPicker:(UIDocumentPickerViewController*)controller didPickDocumentsAtURLs:(nonnullNSArray *)urls {

for(NSURL*urlinurls) {

NSURL *tempURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];

NSData *fileData = [NSData dataWithContentsOfURL:url];

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *filePath = [tempURL.path stringByAppendingPathComponent:url.lastPathComponent];

// If file with same name exists remove it

if([fileManagerfileExistsAtPath:filePath]) {

NSError*error1 =nil;

[fileManagerremoveItemAtPath:filePatherror:&error1];

NSLog(@"error%@", error1);

? ? ? ? }

BOOLsuccess = [fileDatawriteToFile:filePathatomically:YES];

if(success) {

NSLog(@"write file success");

}else{

NSLog(@"write file fail");

return;

? ? ? ? }


NSData *file = [NSData dataWithContentsOfFile:filePath];;

NSLog(@"file:%@", file);

? ? }

}

DocumentTypes可以看官方文檔蘋果官方文檔地址

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容