iOS 压缩和解压,获取解压包内文件以及删除方法总结

最近在开发中需要进行压缩和解压的操作,网上参考了一些大神们的博客和文章,整理一下自己的思路,记录一下。

ZipFile2.gif

http://code.google.com/p/ziparchive/ 上下载ZipArchive.zip,解压后将代码加入工程中,把libz库添加到工程中。然后依照惯例准备几个测试Button和几张图片。

Snip20170425_3.png
//压缩
- (IBAction)CloseZipFile:(UIButton *)sender {

ZipArchive* zip = [[ZipArchive alloc] init];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString * zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;

NSString *image1 = [documentPath stringByAppendingString:@"/1.jpg"] ;
NSString *image2 = [documentPath stringByAppendingString:@"/2.jpg"] ;
NSString *image3 = [documentPath stringByAppendingString:@"/3.jpg"] ;
NSString *image4 = [documentPath stringByAppendingString:@"/4.jpg"] ;

BOOL result = [zip CreateZipFile2:zipFile];
result = [zip addFileToZip:image1 newname:@"1.jpg"];
result = [zip addFileToZip:image2 newname:@"2.jpg"];
result = [zip addFileToZip:image3 newname:@"3.jpg"];
result = [zip addFileToZip:image4 newname:@"4.jpg"];

if( ![zip CloseZipFile2] ){
    zipFile = @"textPic";

  }
}

//解压
- (IBAction)UnzipCloseFile:(UIButton *)sender {

ZipArchive* zip = [[ZipArchive alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

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

}

//移除所有文件
- (IBAction)removeAllFile:(UIButton *)sender {

NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:DocumentsPath];

for (NSString *fileName in enumerator) {

    [[NSFileManager defaultManager] removeItemAtPath:[DocumentsPath stringByAppendingPathComponent:fileName] error:nil];
  }

}

为了获取解压包里面的文件来进行操作,这里额外增加一个获得所有文件名以及全路径的方法

getName.gif
 //获取所有文件名
- (IBAction)localFile:(UIButton *)sender {

    NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:docsDir];

    NSString *fileName;

    while (fileName = [dirEnum nextObject]) {

        NSLog(@"FielName>>>>>> : %@" , fileName);

        NSLog(@"FileFullPath>>>>>>>>>>>>>>> : %@" , [docsDir stringByAppendingPathComponent:fileName]) ;

    }

  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容