如何在iPhone中使用“ZipArchive库”压缩文件?

时间:2011-09-23 06:37:19

标签: iphone objective-c cocoa-touch ios4

我想在我的项目中实施ZipArchive

使用这个库我想将图像等文件存档到zip文件中。

我该怎么做?

2 个答案:

答案 0 :(得分:4)

试试我的代码 邮编:

    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* dPath = [paths objectAtIndex:0];
    NSString* txtfile = [dPath stringByAppendingPathComponent:@"test.txt"];
    NSString* zipfile = [dPath stringByAppendingPathComponent:@"test.zip"];
    ZipArchive* zip = [[ZipArchive alloc] init];
    BOOL ret = [zip CreateZipFile2:zipfile];
    ret = [zip addFileToZip:txtfile newname:@"test.txt"];//zip
    if( ![zip CloseZipFile2] )
    {
        zipfile = @"";
    }
    [zip release];
    NSLog(@"The file has been zipped");

Unzipcode:

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

    NSString* zipfile = [dPath stringByAppendingPathComponent:@"test.zip"] ;
    NSString* unzipto = [dPath stringByAppendingPathComponent:@"test"] ;
    ZipArchive* zip = [[ZipArchive alloc] init];
    if([zip UnzipOpenFile:zipfile] )
    {
        BOOL ret = [zip UnzipFileTo:unzipto overWrite:YES];
        if(NO == ret)
        {
        }
        [zip UnzipCloseFile];
    }
    [zip release];
    NSLog(@"The file has been unzipped");

答案 1 :(得分:2)

此代码可以完美地压缩文件。

ZipArchive *zip = [[ZipArchive alloc] init];
if(![zip UnzipOpenFile:fileToZipPath]) {
//open file is there

            if ([zip CreateZipFile2:newZipFilePath overWrite:YES]) {

                //zipped successfully

                NSLog(@"Archive zip Success");

            } 

        } else  {

            NSLog(@"Failure To Zip Archive");

        }
      }

要解压缩,

if([zip UnzipOpenFile:zipFilePath]) {

            //zip file is there

            if ([zip UnzipFileTo:newFilePath overWrite:YES]) {

                //unzipped successfully

                NSLog(@"Archive unzip Success");

                zipOpened = YES;

            } 

        } else  {

            NSLog(@"Failure To Open Archive");

        }