一、首先介紹minizip 的使用方法
ziparchive是基於開源代碼”MiniZip”的zip壓縮與解壓的Objective-C 的Class,使用起來非常的簡單
方法:從http://code.google.com/p/ziparchive/ 上下載ZipArchive.zip,解壓后將代碼加入工程中,並且把zlib庫添加到工程中
使用方法:
1. 壓縮:ZipArchive可以壓縮多個文件,只需要把文件一一addFileToZip即可.
- ZipArchive* zip = [[ZipArchive alloc] init];
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentpath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
- NSString* l_zipfile = [documentpath stringByAppendingString:@"/test.zip"] ;
- NSString* image1 = [documentpath stringByAppendingString:@"/image1.jpg"] ;
- NSString* image2 = [documentpath stringByAppendingString:@"/image2.jpg"] ;
- BOOL ret = [zip CreateZipFile2:l_zipfile];
- ret = [zip addFileToZip:image1 newname:@"image1.jpg"];
- ret = [zip addFileToZip:image2 newname:@"image2.jpg"];
- if( ![zip CloseZipFile2] )
- {
- l_zipfile = @"";
- }
- [zip release];
2. 解壓縮:
- ZipArchive* zip = [[ZipArchive alloc] init];
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentpath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
- NSString* l_zipfile = [documentpath stringByAppendingString:@"/test.zip"] ;
- NSString* unzipto = [documentpath stringByAppendingString:@"/test"] ;
- if( [zip UnzipOpenFile:l_zipfile] )
- {
- BOOLret = [zip UnzipFileTo:unzipto overWrite:YES];
- if( NO==ret )
- {
- }
- [zip UnzipCloseFile];
- }
- [zip release];
以上摘自:http://www.cnblogs.com/a7345678/archive/2012/06/27/2566125.html 暗夜精靈-鬼才閣。
二、壓縮包含中文的文件時,到windows下解壓后出現亂碼。
這個問題原因是Ios版本的ZipArchive工程中,編碼格式變為UTF-8.然后windows上的編碼格式多數是GBK。
那么打開ZipArchive的源碼,改變編碼方式就行了。
找到函數:
-(BOOL) addFileToZip:(NSString*) file newname:(NSString*) newname
{
if( [_passwordlength] ==0 )
{
ret = zipOpenNewFileInZip(_zipFile,
(constchar*) [newnameUTF8String],//UTF-8方式編碼
&zipInfo,
NULL,0,
NULL,0,
NULL,//comment
Z_DEFLATED,
Z_DEFAULT_COMPRESSION );
}
}
將上述代碼中划線部分,替換為下面部分即可。
(constchar*) [newnamecStringUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)],
已經在mac和windows兩端測試通過,都可以正常壓縮帶有中文的文件,並能正常解壓。
三、解壓帶有中文或者日文的壓縮文件問題
以下轉載自:網友:xin88yue http://www.cocoachina.com/bbs/simple/?t10195.html
原因是:ZipArchive類的解壓函數 -(BOOL) UnzipFileTo:(NSString*) path overWrite:(BOOL) overwrite
在遍歷壓縮文件包,獲取包文件的名字處理上存在Bug.
1. 下面兩行代碼獲取包中當前文件的文件名
unzGetCurrentFileInfo(_unzFile, &fileInfo, filename, fileInfo.size_filename + 1, NULL, 0, NULL, 0);
filename[fileInfo.size_filename] = '\0'; //未尾追加0 結束
此時獲取的文件名是正確的.
2. 但是由char*獲取得到NSString*的轉換方法使用出錯,Mac默認是按UTF8編碼的
//NSString * strPath = [NSString stringWithCString:filename]; //此處得到的 strPath為空,導致函數返回YES,但目錄下無文件
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString * strPath = [NSString stringWithCString:filename encoding:enc];//正確!這個地方應該是跟壓縮時的編碼對應上才對。
這樣就OK了!