iOS从“文件”中选择文件

关键词:iOS, 文件, file, UIDocumentPicker

从系统应用“文件”中选择文件

步骤

实现代理

UIDocumentPickerDelegate

代理方法

#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
    NSURL *url = urls.firstObject;
    if (url == nil) {
        return;
    }
    [url startAccessingSecurityScopedResource];
    NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
    NSError *error;
    [coordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
        NSString *fileName = [newURL lastPathComponent];
        NSString *filePath = [EDLiveFileManager getLiveResourceFilePathWithName:fileName];
        //需要把文件拷贝到沙盒的其他地方再使用
        [DCFileManager copyWithPath:newURL.path toPath:filePath];
    }];
    [url stopAccessingSecurityScopedResource];
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
    [controller dismissViewControllerAnimated:YES completion:nil];
}

显示页面

NSArray *types = @[@"public.data"];
UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
picker.delegate = self;
[self presentViewController:picker animated:YES completion:nil];

模式

typedef NS_ENUM(NSUInteger, UIDocumentPickerMode) {
    UIDocumentPickerModeImport,//导入
    UIDocumentPickerModeOpen,//打开
    UIDocumentPickerModeExportToService,//导出
    UIDocumentPickerModeMoveToService//直接访问
}