通过UIDocumentPickerViewController 访问iPhone自带应用“Files(文件) APP”。
前提条件:
1:iOS 系统为11.0及以上
2:Xcode中开启iCloud配置
导入文件功能
NSArray *documentTypes = @[@"com.adobe.pdf",@"public.content", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.apple.keynote.key", @"com.microsoft.word.doc",@"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc]initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeImport];
documentPickerViewController.delegate = self;
[self presentViewController:documentPickerViewController animated:YES completion:nil];
#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
NSString *fileName = [array lastObject];
fileName = [fileName stringByRemovingPercentEncoding];
NSLog(@"文件路径%@",[url absoluteString]);
}
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
//获取授权
BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
if (fileUrlAuthozied) {
//通过文件协调工具来得到新的文件地址,以此得到文件保护功能
NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
NSError *error;
[fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
//读取文件
NSString *fileName = [newURL lastPathComponent];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
if (error) {
//读取出错
} else {
NSLog(@"上传===%@",fileName);
//上传
// [self uploadingWithFileData:fileData fileName:fileName fileURL:newURL];
}
[self dismissViewControllerAnimated:YES completion:NULL];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
} else {
//授权失败
}
}
初始化方法
-(instancetype)initWithDocumentTypes:(NSArray <NSString >)allowedUTIs inMode:(UIDocumentPickerMode)mode
mode :确定目标导入模式
UIDocumentPickerModeImport,导入(将外部文档复制到您的应用中,使原始文档保持不变)
UIDocumentPickerModeOpen,打开(提供对文档的访问权限,可以在适当位置进行编辑)
UIDocumentPickerModeExportToService,导出(将应用内的文档导出到所选的外部目标位置)
UIDocumentPickerModeMoveToService 移动(在应用程序中定位文档的外部目标)
allowedUTIs 老版本写法 新的写法:告诉文档选择器我想要的文件类型
[String(kUTTypePDF),String(kUTTypePNG),String(kUTTypeJPEG),]
directoryURL
设置此属性可以为文档选择器指定起始目录