天天看点

iOS中压缩和解压缩文件--ZipArchive

    之前在做项目的时候,从网络请求的数据有可能是压缩文件,如何解压呢,这个是个问题,网上看了一看有很多,我自己就找了一个感觉不错的第三方,使用的时候也简单,就来试试吧。使用ZipArchive来进行iOS的压缩和解压缩文件

    我用的第三方文件是ZipArchive,这个是大家经常用到的。

将第三方倒入到工程中就可以

调用头文件

#import "ZipArchive.h"
           

首先是压缩文件

- (void)zipFunction
{
    zip = [[ZipArchive alloc] init];
    NSString *documentPath = [self documentsPath];
    NSString * zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
    
    NSString * image1 = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"jpg" inDirectory:nil];
    NSString * image2 = [[NSBundle mainBundle] pathForResource:@"b" ofType:@"jpg" inDirectory:nil];
    BOOL result = [zip CreateZipFile2:zipFile];
    result = [zip addFileToZip:image1 newname:@"a.jpg"];
    result = [zip addFileToZip:image2 newname:@"b.jpg"];
    if( ![zip CloseZipFile2] ){
        zipFile = @"";
    }
    [zip release];
    NSLog(@"%@",NSHomeDirectory());
}
           

然后解压函数

- (void)unzip
{
    zip = [[ZipArchive alloc] init];
    NSString *documentPath = [self documentsPath];
    NSString* zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
    NSString* unZipTo = [documentPath stringByAppendingString:@"/images"] ;
    if( [zip UnzipOpenFile:zipFile] ){
        BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
        if( NO==result ){
            //添加代码
        }
        [zip UnzipCloseFile];

        NSString * imageField = [unZipTo stringByAppendingPathComponent:@"a.jpg"];
        NSData * imagedata = [NSData dataWithContentsOfFile:imageField];
        UIImage * image = [UIImage imageWithData:imagedata];
        
        UIImageView * iamgePic = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
        
        [iamgePic setImage:image];
        
        [self.view addSubview:iamgePic];

    }
    [zip release];
}
           

这样就把a图片解压出来了

很简单吧。。。。。

剩下的就是自己调用了。。。。。。