iOS 将文件压缩成zip包再上传至服务器

运用ssziparchive 来完成zip 压缩。

/**
 初始化 UIDocumentPickerViewController
 
 @param allowedUTIs 支持的文件类型数组
 "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"
 @param mode 支持的共享模式
 */
- (UIDocumentPickerViewController *)documentPickerVC {
    
   NSArray * array = @[@"public.data",@"public.content",@"public.audiovisual-content",@"public.movie",@"public.audiovisual-content",@"public.video",@"public.audio",@"public.text",@"public.data",@"public.zip-archive",@"com.pkware.zip-archive",@"public.composite-content",@"public.text",@"com.microsoft.powerpoint.ppt",@"com.microsoft.powerpoint.​pptx",];
    
    if (!_documentPickerVC) {
        NSArray *types = array;
        self.documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
        // 设置代理
        _documentPickerVC.delegate = self;
        if (@available(iOS 11.0, *)) {
            _documentPickerVC.allowsMultipleSelection = YES;
        } else {
            // Fallback on earlier versions
        }
        // 设置模态弹出方式
        _documentPickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return _documentPickerVC;
}
- (NSString *)tempZipPath {
    NSString *path = [NSString stringWithFormat:@"%@.zip",
                      NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]]
                     ;
    return path;
}

- (NSString *)_cachesPath:(NSString *)directory {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject
                      stringByAppendingPathComponent:@"zipArchive"];
    if (directory) {
        path = [path stringByAppendingPathComponent:directory];
    }

    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];

    return path;
}

按钮点击出现文件选择:

   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weak_self presentViewController:weak_self.documentPickerVC animated:false completion:^{
                    if (@available(iOS 11.0, *)) {
                        weak_self.documentPickerVC.allowsMultipleSelection = YES;
                    }
                }];
                ```

文件选择完成之后的代理:

```c
#pragma mark -选择文件
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    
    NSString *outputPath = [self _cachesPath:@"Zipped"];
    NSString *userName = DSStringValue(self.modelRestartTreatPlanSubmit.CaseMainItem.PatientName);
    
    NSString *archivePath = [outputPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip", userName]];
//    NSString *archivePath = [outputPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip", @"archive"]];
    NSMutableArray *arr = [NSMutableArray array];
    
    for (NSURL *url in urls) {
        BOOL fileUrlAuthozied = [url startAccessingSecurityScopedResource];
        if (!fileUrlAuthozied){
            [self showMessage:@"文件授权失败,请授权"];
            return;
        }
        // 通过文件协调工具来得到新的文件地址,以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL * _Nonnull newURL) {

            NSString *filePath2 = newURL.path ;;
            [arr addObject:filePath2];
        }];
    }
    NSArray *inputPaths = [arr copy];
    BOOL success = [SSZipArchive createZipFileAtPath:archivePath withFilesAtPaths:inputPaths];

    for (NSURL *url in urls) {
        [url stopAccessingSecurityScopedResource];
    }
    if (success) {
        NSLog(@"Success zip");

    } else {
        NSLog(@"No success zip");
    }

        if(success){

            NSData *fileData = [NSData dataWithContentsOfFile:archivePath options:NSDataReadingMappedIfSafe error:nil];

            // 上传
            dispatch_async(dispatch_get_main_queue(), ^{
            [self showLoading];
            });
            [[STHeadUpload headUploadShareInstance]requestActionFile:archivePath fileData:fileData followRequestName:AddUpdateRestartTreatPlan3Method progressBlock:^(float progress) {
                                    
                                } successBlock:^(NSString * _Nonnull url) {
                                    
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [self hideLoading];
                                        
                                        self.modelRestartTreatPlanSubmit.CaseTeethModelItem.LocalPath = DSStringValue(url);
                                        [self.arrSubmit[2] setObject:DSStringValue(url) forKey:@"LocalPath"];

//                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            
                                            [UIView performWithoutAnimation:^{//去掉刷新
                                                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                                            }];

//                                        //清除缓存
                                        [[NSFileManager defaultManager] removeItemAtPath:archivePath error:nil];

                                    });
                                } failedBlock:^(NSString * _Nonnull error) {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [self hideLoading];
                                        //清除缓存
                                      [[NSFileManager defaultManager] removeItemAtPath:archivePath error:nil];
                                    });
                                }];
//            [self dismissViewControllerAnimated:YES completion:NULL];

            NSLog(@"fileName : %@", _zipPath);

        }else{
            NSLog(@"No success zip");
        }
          
 
}

注意:所有的文件都需要授权 不然会访问不到文件内容

你可能感兴趣的:(ios,服务器,cocoa,objective-c,xcode)