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

时间:2016-04-23 11:26:32

标签: ios zip multiple-files

我想制作一个包含多个文档的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文件中的一个文档?

2 个答案:

答案 0 :(得分:1)

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

[za CreateZipFile2:zipFilePath append:YES];

答案 1 :(得分:0)

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"];
}