技术重塑第三方工具类IOS 知识积累

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

2017-04-25  本文已影响4054人  估唔到

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

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

    }

  }
上一篇下一篇

猜你喜欢

热点阅读