如何在 iOS 中的一个 zip 文件中添加多个文档?

How to add multiple Documents in a zip file in iOS?

我想制作一个包含多个文档的zip文件,文档取自我的文档目录。

BOOL isDir=NO;

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSArray *subpaths;
for(int i=0; i<[arrdocument count]; i++)
{
    NSString *toCompress = [arrdocument objectAtIndex:i];
    NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
        subpaths = [fileManager subpathsAtPath:pathToCompress];
    } else if ([fileManager fileExistsAtPath:pathToCompress]) {
        subpaths = [NSArray arrayWithObject:pathToCompress];
    }

    NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"myZipFileName2.zip"];

    ZipArchive *za = [[ZipArchive alloc] init];
    [za CreateZipFile2:zipFilePath];

    if (isDir) {
        for(NSString *path in subpaths){
            NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
            if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
                [za addFileToZip:fullPath newname:path];
            }
        }
    } else {
        [za addFileToZip:pathToCompress newname:toCompress];
    }
}

但是当我查看 zip 文件时,它只显示 zip 文件中的一个文档?

您似乎在每次循环迭代中都重新创建了 zip 文件。您应该改为将 zip 文件的创建移出循环,或者在创建 zip 文件时仅指定追加,如下所示:

[za CreateZipFile2:zipFilePath append:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *zipFile = [documentsDirectory stringByAppendingPathComponent:@"compressed.zip"];
ZipArchive *zip = [[ZipArchive alloc] init];
BOOL result = [zip CreateZipFile2:zipFile];
if(result){
    NSError *error;
    NSArray *allFiles = arrdocument;
    for(int index = 0; index<allFiles.count; index++){
        id singleFileName = [allFiles  objectAtIndex:index];
        NSString *singleFilePath = [documentsDirectory stringByAppendingPathComponent:singleFileName];
        [zip addFileToZip:singleFilePath newname:singleFileName];
    }
    [zip CloseZipFile2];
}else{
    [self showErrorMessage:@"Unable to to create zip file. Please try again later"  withTitle:@"Error"];
}