最近需要用到文件導(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可以看官方文檔蘋果官方文檔地址