利用UIDocumentPickerViewController从手机上传文件到app

有时候会有这么一些需求,需要用户上传自己的一些xml,doc,pdf文档.可是iOS上并没有直观的文件管理系统.这时候Document Picker就可以帮助我们访问iCould,dropBox等应用中的文件.然后进行相关操作.

使用

首先应该在项目中添加对iCould的支持, 在TARGETS-Capabilities中把iCloud的按钮打开,勾选iCloud Documents.

然后开始初始化一个Document Picker,并且声明所支持文件的类型.然后就会弹出一个iCloud Drive的文档选择器.这个选择器需要我们在手机上登录自己的iCloud的账号,然后我们就可以选择在iCloud中存放的文件.

1
2
3
4
5
6
7
8
9
NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:documentPicker animated:YES completion:nil];

选择之后根据documentPicker的代理方法- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url; 获取到文档的地址.然后NSFileCoordinator读取文件地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
BOOL fileUrlAuthozied = [url startAccessingSecurityScopedResource];
if(fileUrlAuthozied){
NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *fileData;
[fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
NSString *fileName = [newURL lastPathComponent];
NSString *fileStr = [NSString stringWithContentsOfURL:newURL encoding:NSUTF8StringEncoding error:nil];
[self dismissViewControllerAnimated:YES completion:NULL];
}];
[url stopAccessingSecurityScopedResource];
}else{
//Error handling
}
}