美文网首页iOS开发技术讨论iOS技术点
iOS 文件浏览器UIDocumentPickerViewCon

iOS 文件浏览器UIDocumentPickerViewCon

作者: 小榕 | 来源:发表于2019-07-18 18:59 被阅读0次

最近需要用到文件导入导出功能,导出使用类UIDocumentInteractionController很容易实现,但文件导入却找了好久都没找到符合需求的,本来找到UIDocumentBrowserViewController,以为可以了,可是并不能满足需求,可能是我不会用吧,而且UIDocumentBrowserViewController需要iOS11以上的系统版本才支持,最终看到一篇文章,让我见到了光明:https://www.jianshu.com/p/607b96ddc757,使用UIDocumentPickerViewController完美解决问题,支持iOS8。

话不多说,上代码!!

1、本地文件导出

#pragma mark 导出

- (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、导入文件

#pragma mark 导入

- (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可以看官方文档苹果官方文档地址

相关文章

网友评论

    本文标题:iOS 文件浏览器UIDocumentPickerViewCon

    本文链接:https://www.haomeiwen.com/subject/rpjrlctx.html