1.模态打开系统自带的系统文件 选取文件
UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithURL:[NSURL fileURLWithPath:fullPath] inMode:UIDocumentPickerModeExportToService];
// 设置代理
documentPickerVC.delegate = self;
// 设置模态弹出方式
documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
[self.navigationController presentViewController:documentPickerVC animated:YES completion:nil];
2.获取沙盒路径
// 获得文件沙盒地址
- (NSString *)getNativeFilePath:(NSString *)fileName {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *munu = [NSString stringWithFormat:@"%@/%@",@"downLoad",fileName];
NSString *filePath = [path stringByAppendingPathComponent:munu];
// 判断是否存在,不存在则创建
NSFileManager *fileManager = [NSFileManager defaultManager];
// fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
BOOL isDir = NO;
NSMutableArray *theArr = [[filePath componentsSeparatedByString:@"/"] mutableCopy];
[theArr removeLastObject];
NSString *thePath = [theArr componentsJoinedByString:@"/"];
BOOL existed = [fileManager fileExistsAtPath:thePath isDirectory:&isDir];
if ( !(isDir == YES && existed == YES) ) { // 如果文件夹不存在
[fileManager createDirectoryAtPath:thePath withIntermediateDirectories:YES attributes:nil error:nil];
}
return filePath;
}
3.文件写入制定的路径
BOOL downResult = [fileData writeToFile:fullPath atomically:YES];
- UIDocumentPickerDelegate的代理方法
pragma mark - UIDocumentPickerDelegate
-
(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 { // [self uploadingWithFileData:fileData fileName:fileName fileURL:newURL]; }
// [self dismissViewControllerAnimated:YES completion:NULL];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
} else {
// 授权失败
}
}