場景:從服務端下載文件到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 }