最近项目中服务器方返回了zip文件类型的文件,在网上搜了好多资料做成一个Demo,这里用来详解一下。

ZipArchive类来源于网络。还望多多交流。

 

1、首先添加libz.dylib框架

2、前往http://code.google.com/p/ziparchive/downloads/list下载所需要的第三方文件,并将其导入到项目中。

3、代码:

 

 

    ZipArchive* zip = [[ZipArchivealloc] init];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *dcoumentpath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

    //获取解压缩文件

    NSString* l_zipfile = [dcoumentpath stringByAppendingString:[NSString stringWithFormat:@"/%@",ZipName]] ;

    //获取路径  aaa.zip  压缩包解压缩后会出现  aaa  文件夹  去aaa文件夹中取文档和子文件夹里面的文档

    NSArray *arr = [ZipName componentsSeparatedByString:@"."];

    NSString* unzipto = [dcoumentpath stringByAppendingString:[NSStringstringWithFormat:@"/%@",[arr objectAtIndex:0]]] ;

    

    NSString *str = [[NSString alloc] init];

    str = unzipto;

    if( [zip UnzipOpenFile:l_zipfile] ) {

        BOOL ret = [zip UnzipFileTo:unzipto overWrite:YES];

        if( NO==ret ) { }

        [zip UnzipCloseFile];

    }

    [zip release];

    

    

    //解压缩后或多处一个   __MACOSX 文件夹   做删除操作

    NSFileManager *fileManager = [NSFileManagerdefaultManager];

    NSString *strpath = [unzipto stringByAppendingFormat:@"/__MACOSX"];

    [fileManager removeItemAtPath:strpath error:nil];

    

 

    NSFileManager *myFileManager=[NSFileManagerdefaultManager];

    NSDirectoryEnumerator *myDirectoryEnumerator = [myFileManager enumeratorAtPath:unzipto];

       

    //列举目录内容

    while((unzipto=[myDirectoryEnumerator nextObject])!=nil)

    {

        NSLog(@"%@",unzipto);

        //获取子文件夹路径

        NSString *str_path = [str stringByAppendingFormat:@"/%@",unzipto];

        if ([self isPathorFile:str_path]) {

            NSLog(@"目录");

        }else{

            NSLog(@"文件");

        }

    }

    [str release];

    

    

 

/**

 *@brief判断一个路径是文件还是文件夹

 *

 *@param path 路径

 *

 *@return返回BOOL值

 */

-(BOOL)isPathorFile:(NSString *)path

{

    BOOL isDir;

    NSString *documentsDir = path;

    if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDir isDirectory:&isDir] && isDir) {

        NSLog(@"directory");

        isDir = YES;

    }else{

        NSLog(@"file");

        isDir = NO;

    }

    return isDir;

}