文件导入
- (void)importFile {
NSArray *types = @[]; // 可以选择的文件类型
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:documentPicker animated:YES completion:nil];
}
#pragma mark - <UIDocumentPickerDelegate>
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls API_AVAILABLE(ios(11.0)){
NSURL *url = urls[0];
BOOL canAccessingResource = [url startAccessingSecurityScopedResource];
if(canAccessingResource) {
NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
NSError *error;
[fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
NSData *fileData = [NSData dataWithContentsOfURL:newURL];
NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [arr lastObject];
NSString *desFileName = [documentPath stringByAppendingPathComponent:self.fileName];
[fileData writeToFile:desFileName atomically:YES];
[self dismissViewControllerAnimated:YES completion:NULL];
}];
if (error) {
// error handing
}
} else {
// startAccessingSecurityScopedResource fail
}
[url stopAccessingSecurityScopedResource];
}
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
NSLog(@"取消");
}
文件导出
- (void)exportFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
// 保存文件的名称
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
UIDocumentPickerViewController *vccc = [[UIDocumentPickerViewController alloc]initWithURL:[NSURL fileURLWithPath:filePath] inMode:UIDocumentPickerModeExportToService];
[self presentViewController:vccc animated:YES completion:nil];
}
Demo
MacCatalyst文件导入导出