有时候会有这么一些需求,需要用户上传自己的一些xml,doc,pdf文档.可是iOS上并没有直观的文件管理系统.这时候Document Picker就可以帮助我们访问iCould,dropBox等应用中的文件.然后进行相关操作.
使用
首先
应该在项目中添加对iCould的支持, 在TARGETS-Capabilities中把iCloud的按钮打开,勾选iCloud Documents.
然后开始初始化一个Document Picker,并且声明所支持文件的类型.然后就会弹出一个iCloud Drive的文档选择器.这个选择器需要我们在手机上登录自己的iCloud的账号,然后我们就可以选择在iCloud中存放的文件.
NSArray*types =@[
@"public.data",
@"com.microsoft.powerpoint.ppt",
@"com.microsoft.word.doc",
@"com.microsoft.excel.xls",
@"com.microsoft.powerpoint.pptx",
@"com.microsoft.word.docx",
@"com.microsoft.excel.xlsx",
@"public.avi",
@"public.3gpp",
@"public.mpeg-4",
@"com.compuserve.gif",
@"public.jpeg",
@"public.png",
@"public.plain-text",
@"com.adobe.pdf"
];
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:documentPicker animated:YES completion:nil];
选择之后根据documentPicker
的代理方法- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls;
获取到文档的地址.然后NSFileCoordinator
读取文件地址
- (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) {
NSError *error = nil;
NSString *fileName = [newURL lastPathComponent];
NSString *fileStr = [NSString stringWithContentsOfURL:newURL encoding:NSUTF8StringEncoding error:&error];
NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
if (error) {
NSLog(@"文件读取出错: %@",error);
}else{
NSLog(@"上传: %@",fileName);
// [self uploadingWithFileData:fileData fileName:fileName fileURL:newURL];
}
[self dismissViewControllerAnimated:YES completion:NULL];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
}else{
//Error handling
NSLog(@"授权失败");
}
}
网友评论