ios UIDocumentPickerViewController 打開文件夾
直接給代碼 你們拿去玩吧
@interface SUViewController ()<UIDocumentPickerDelegate>
@property (nonatomic, strong) UIDocumentPickerViewController *documentPickerVC;
@end
@implementation SUViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"122");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self presentViewController:self.documentPickerVC animated:YES completion:nil];
});
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UIDocumentPickerViewController *)documentPickerVC {
if (!_documentPickerVC) {
/**
初始化
@param allowedUTIs 支持的文件類型數(shù)組
@param mode 支持的共享模式
*/
NSArray *types = @[@"public.content",@"public.text"];
self.documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
//設(shè)置代理
_documentPickerVC.delegate = self;
//設(shè)置模態(tài)彈出方式
_documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
}
return _documentPickerVC;
}
#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
//獲取授權(quán)
BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
if (fileUrlAuthozied) {
//通過文件協(xié)調(diào)工具來得到新的文件地址资昧,以此得到文件保護(hù)功能
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) {
//讀取出錯(cuò)
} else {
//上傳
NSLog(@"fileName : %@", fileName);
// [self uploadingWithFileData:fileData fileName:fileName fileURL:newURL];
}
[self dismissViewControllerAnimated:YES completion:NULL];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
} else {
//授權(quán)失敗
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self presentViewController:self.documentPickerVC animated:YES completion:nil];
}