iOS 使用ZipArchive壓縮文件

01 +(NSString *)zipFiles:(NSArray *)paramFiles
02 {
03     //生成zip文件名字
04     NSString * zipFileName = [[CUtils generateRndString] stringByAppendingPathExtension:@"zip"];
05     //取得zip文件全路徑
06     NSString * zipPath = [[CUtils documentPath] stringByAppendingPathComponent:zipFileName];
07      
08     //判斷文件是否存在,若是存在則刪除文件
09     NSFileManager * fileManager = [NSFileManager defaultManager];
10     @try
11     {
12         if([fileManager fileExistsAtPath:zipPath])
13         {
14             if(![fileManager removeItemAtPath:zipPath error:nil])
15             {
16                 CCLog(@"Delete zip file failure.");
17             }
18         }
19     }
20     @catch (NSException * exception) {
21         CCLog(@"%@",exception);
22     }
23      
24     //判斷須要壓縮的文件是否爲空
25     if(paramFiles == nil || [paramFiles count] == 0)
26     {
27         CCLog(@"The files want zip is nil.");
28         return nil;
29     }
30      
31     //實例化並建立zip文件
32     ZipArchive * zipArchive = [[ZipArchive alloc] init];
33     [zipArchive CreateZipFile2:zipPath];
34      
35     //遍歷文件
36     for(NSString * fileName in paramFiles)
37     {
38         NSString * filePath = [[CUtils documentPath] stringByAppendingPathComponent:fileName];
39         if([fileManager fileExistsAtPath:filePath])
40         {   //添加文件到壓縮文件
41             [zipArchive addFileToZip:filePath newname:fileName];
42         }
43     }
44     //關閉文件
45     if([zipArchive CloseZipFile2])
46     {
47         CCLog(@"Create zip file success.");
48         [zipArchive release];
49         return zipPath;
50     }
51     [zipArchive release];
52     return nil;
53 }
相關文章
相關標籤/搜索