最近在开发中需要进行压缩和解压的操作,网上参考了一些大神们的博客和文章,整理一下自己的思路,记录一下。
![](https://images2017.cnblogs.com/blog/1061766/201710/1061766-20171013172859059-550659875.gif)
![](https://images2017.cnblogs.com/blog/1061766/201710/1061766-20171013172934434-260181991.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];
}
}
为了获取解压包里面的文件来进行操作,这里额外增加一个获得所有文件名以及全路径的方法
![](https://images2017.cnblogs.com/blog/1061766/201710/1061766-20171013173016434-1206926568.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]) ;
}
}