UIDocumentPickerViewController使用

场景:从服务端下载文件到iPhone文件夹或者从iPhone本地文件夹选择文件上传服务端

UIDocumentPickerViewController有四种模式:

1 typedef NS_ENUM(NSUInteger, UIDocumentPickerMode) {
2     UIDocumentPickerModeImport,
3     UIDocumentPickerModeOpen,
4     UIDocumentPickerModeExportToService,
5     UIDocumentPickerModeMoveToService
6 } API_DEPRECATED("Use appropriate initializers instead",ios(8.0,14.0)) API_UNAVAILABLE(tvos);
  • UIDocumentPickerModeImport:用户选择一个外部文档,文档选择器拷贝该文档到应用沙盒,不会修改源文档。
  • UIDocumentPickerModeOpen:打开一个外部文档,用户可以修改该文档。
  • UIDocumentPickerModeExportToService:文档选择器拷贝文档到一个外部路径,不会修改源文档。
  • UIDocumentPickerModeMoveToService:拷贝文档到外部路径,同时可以修改该拷贝。

1、下载文件存储到iPhone 本地文件夹

  1 -(void)requestImageUrl:(NSString *)imageUrl {
  2     [[DDLoading shared] show];
  3   
  4 //     // 下载图片之前先检查本地是否已经有图片
  5 //     UIImage * image = [self loadLocalImage:imageUrl];
  6 //     NSData *imageData = UIImagePNGRepresentation(image);
  7 //     //如果图片存在直接跳出;不用下载了
  8 //     if (imageData) {
  9 //       self.successBlock(imageData);
 10 //       return;
 11 //     }
 12    
 13    // 没有本地图片
 14    // 创建URL对象
 15 //    NSURL *url = [NSURL URLWithString:[imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
 16       NSURL *url = [NSURL URLWithString:[imageUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
 17    // 创建request对象
 18    NSURLRequest *request = [NSURLRequest requestWithURL:url];
 19    
 20    // 使用URLSession来进行网络请求
 21    // 创建会话配置对象
 22    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
 23    // 创建会话对象
 24    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
 25    // 创建会话任务对象
 26    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
 27         if (data) {
 28             // 将下载的数据传出去,进行UI更新
 29             DebugLog(@"文件下载成功~~~~~~%@",data);
 30                 // 下载完成,将图片保存到本地
 31                 [data writeToFile:[self imageFilePath:imageUrl] atomically:YES];
 32         
 33                 dispatch_async(dispatch_get_main_queue(), ^{
 34                      //遮罩关闭
 35                     NSString * urlPath =[self imageFilePath:imageUrl] ;
 36                     UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@",urlPath]] inMode:UIDocumentPickerModeExportToService];
 37                        documentPicker.delegate = self;
 38                        documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
 39                        [Singleton.rootViewController presentViewController:documentPicker animated:YES completion:nil];
 40                 });
 41           
 42             
 43         }
 44         if (error) {
 45             DebugLog(@"文件下载失败~~~~~~%@",error);
 46              dispatch_async(dispatch_get_main_queue(), ^{
 47              //遮罩关闭
 48              });
 49              self.jsapiCallback(@{@"result":@"0",@"errorMsg":@"文件下载失败"});
 50 // 51 //
 52         }
 53     }];
 54 
 55    // 创建的task都是挂起状态,需要resume才能执行
 56    [task resume];
 57 }
 58 - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
 59     DebugLog(@"*************************存储成功");
 60     DebugLog(@"*************************%@",urls);
 61     self.jsapiCallback(@{@"result":@"1"});
 62 }
 63 
 64 // called if the user dismisses the document picker without selecting a document (using the Cancel button)
 65 - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller{
 66    DebugLog(@"*************************存储失败");
 67     self.jsapiCallback(@{@"result":@"0",@"errorMsg":@"用户取消操作"});
 68 }
 69 
 70 - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
 71    DebugLog(@"*************************");
 72 }
 73 //
 74 - (NSString *)imageFilePath:(NSString *)imageUrl {
 75     // 1、获取caches文件夹路径
 76     NSString * cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
 77     
 78     // 2、创建DownloadImages文件夹
 79     NSString * downloadImagesPath = [cachesPath stringByAppendingPathComponent:@"DownloadImages"];
 80 
 81     // 3、创建文件管理器对象
 82     NSFileManager * fileManager = [NSFileManager defaultManager];
 83     
 84     // 4、判断文件夹是否存在
 85     if (![fileManager fileExistsAtPath:downloadImagesPath])
 86     {
 87         [fileManager createDirectoryAtPath:downloadImagesPath withIntermediateDirectories:YES attributes:nil error:nil];
 88     }
 89     
 90     // 5、拼接图片在沙盒中的路径
 91     /*
 92       因为每一个图片URL对应的是一张图片,而且URL中包含了文件的名称,所以可以用图片的URL来唯一表示图片的名称
 93       因为图像URL中有"/","/"表示的是下级目录的意思,要在存入前替换掉,所以用"_"代替
 94     */
 95     NSArray *imageArr = [imageUrl componentsSeparatedByString:@"/"];
 96     NSString * imageName = [imageArr lastObject];
 97     NSString * imageFilePath = [downloadImagesPath stringByAppendingPathComponent:imageName];
 98 
 99     // 6、返回文件路径
100     return imageFilePath;
101 }

 

2、选择iPhone本地文件送给服务端

 1 - (IBAction)shareAction:(id)sender {
 2     NSArray *types = @[@"public.content"];可选文件类型 types需要传入一个uniform type identifiers (UTIs)数组。关于UTIs的官方文档
 3     UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
 4     documentPicker.delegate = self;
 5     documentPicker.modalPresentationStyle = UIModalPresentationPageSheet;
 6     [self presentViewController:documentPicker animated:YES completion:nil];
 7     
 8 }
 9 
10 - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
11     BOOL canAccessingResource = [url startAccessingSecurityScopedResource];
12     if(canAccessingResource) {
13         NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
14         NSError *error;
15         [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
16             NSData *fileData = [NSData dataWithContentsOfURL:newURL];
17             NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
18             NSString *documentPath = [arr lastObject];
19             NSString *desFileName = [documentPath stringByAppendingPathComponent:@"file"];
20             [fileData writeToFile:desFileName atomically:YES];
21             NSLog(@"point_test_log%@",desFileName);
22             [self dismissViewControllerAnimated:YES completion:NULL];
23         }];
24         if (error) {
25             // error handing
26         }
27     } else {
28         // startAccessingSecurityScopedResource fail
29     }
30     [url stopAccessingSecurityScopedResource];
31 }

 

posted @ 2021-01-05 18:08  奶瓶瓶🍼  阅读(5773)  评论(0编辑  收藏  举报