iOS 壓縮和解壓,獲取解壓包內文件以及刪除方法總結


最近在開發中需要進行壓縮和解壓的操作,網上參考了一些大神們的博客和文章,整理一下自己的思路,記錄一下。

從http://code.google.com/p/ziparchive/ 上下載ZipArchive.zip,解壓后將代碼加入工程中,把libz庫添加到工程中。然后依照慣例准備幾個測試Button和幾張圖片。

//壓縮
- (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];
  }

}

為了獲取解壓包里面的文件來進行操作,這里額外增加一個獲得所有文件名以及全路徑的方法

//獲取所有文件名
- (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]) ;

    }

  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM