//调用该对象
-(void)btnclick{
self.documentPickerVC.hidesBottomBarWhenPushed=YES;
[self presentViewController:self.documentPickerVC animated:YES completion:nil];
}
//初始化对象
- (UIDocumentPickerViewController *)documentPickerVC {
if (!_documentPickerVC) {
//这样添加的参数可以解决“预览文件是灰色而导致无法选择”
NSArray * arr=@[(__bridge NSString *) kUTTypeContent,
(__bridge NSString *) kUTTypeData,
(__bridge NSString *) kUTTypePackage,
(__bridge NSString *) kUTTypeDiskImage,
@"com.apple.iwork.pages.pages",
@"com.apple.iwork.numbers.numbers",
@"com.apple.iwork.keynote.key"];
self.documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:arr inMode:UIDocumentPickerModeOpen];
_documentPickerVC.delegate = self;
//设置模态弹出方式
// _documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
}
return _documentPickerVC;
}
//实现代理
#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 {
NSLog(@"上传===%@",fileName);
//上传
// [self uploadingWithFileData:fileData fileName:fileName fileURL:newURL];
}
[self dismissViewControllerAnimated:YES completion:NULL];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
} else {
//授权失败
}
}
配置icoud
plist文件:
UIFileSharingEnabled
- 可以从iTunes中导入文件到Documents文件夹中- Supports opening documents in place - BOOL YES确保local file provider可以访问你的Documents文件夹
这个是按钮点击调用该对象后的页面效果: