//注意事项, info.plist 增加
Application supports iTunes file sharing: YES
Supports opening documents in place: YES
附录: 从系统Files App中读取文件
- (void)presentDocumentPicker {
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"];
/*
UIDocumentPickerModeImport,//导入
UIDocumentPickerModeOpen,//打开
UIDocumentPickerModeExportToService,//导出
UIDocumentPickerModeMoveToService//直接访问
*/
UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];//UIDocumentPickerModeImport
documentPickerViewController.delegate = self;
[self presentViewController:documentPickerViewController animated:YES completion:nil];
}
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls API_AVAILABLE(ios(11.0)) {
//获取授权
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) {
[self handleReadingItemAtURL:newURL];
// [self dismissViewControllerAnimated:YES completion:NULL];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
} else {
//授权失败
[self mb_showMessage:NSLocalizedString(@"打开失败", nil)];
}
}
- (void)handleReadingItemAtURL:(NSURL *)newURL {
//自身App路径判断
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
if ([newURL.absoluteString containsString:documentsPath]) {
[self openFileWithUrl:newURL];
return;
}
[self mb_Loading];
NSString *fileName = [newURL lastPathComponent];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
if (error) {
NSLog(@"error: %@",error);
[self mb_showMessage:NSLocalizedString(@"打开失败", nil)];
} else {
/*
file:///private/var/mobile/Containers/Data/Application/289E3E40-52D3-4187-8FC0-CE8EBABD565E/Documents/example2.MOV
*/
NSLog(@"coordinateReadingItemAtURL: %@",newURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
BOOL ret = [fileData writeToFile:path atomically:YES];
NSLog(@"写文件:%@", ret?@"成功":@"失败");
if (ret) {
dispatch_async(dispatch_get_main_queue(), ^{
[self mb_hideHUD];
NSURL *playerURL = [NSURL fileURLWithPath:path];
[self openFileWithUrl:playerURL];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
[self mb_showMessage:NSLocalizedString(@"打开失败", nil)];
});
}
});
}
}