用UIDocumentPickerViewController来获取iCloud里的文件
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;
[self presentViewController:documentPicker animated:YES completion:nil];
在UIDocumentPickerDelegate的回调方法里处理获取到的文件
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(nonnull NSArray<NSURL *> *)urls {
//授权
BOOL fileAuthorized = [urls.firstObject startAccessingSecurityScopedResource];
if (fileAuthorized) {
NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc]init];
NSError *error;
[fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL * _Nonnull newURL) {
//读取文件
NSString *fileName = [newURL lastPathComponent];
NSString *fileNameUtf8 = [fileName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
if (error) {
NSLog(@"读取错误");
}else {
NSLog(@"fileName: %@\nfileUrl: %@", fileName, newURL);
//写入沙盒Documents
NSString *path = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@", fileNameUtf8]];
[fileData writeToFile:path atomically:YES];
NSLog(@"filePath: %@", path);
if ([path hasSuffix:@".pdf"]) {
DTWebViewController *webView = [[DTWebViewController alloc]init];
webView.title = fileName;
[webView loadWebFileSring:fileNameUtf8];
[self.navigationController pushViewController:webView animated:YES];
}
}
[self dismissViewControllerAnimated:YES completion:nil];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
}else {
NSLog(@"授权失败");
}
}
![](https://img.haomeiwen.com/i10317259/dd56564b8ac597d1.gif)
PS:WKWebView加载沙盒路径PDF
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:[filePath stringByAppendingPathComponent:@"xxx.pdf"]];
[self.wkWebView loadFileURL:url allowingReadAccessToURL:url];
网友评论