2016-04-23 105 views
3

我想要一個zip文件包含多個文檔,文檔從我的文檔目錄中獲取。如何在iOS中的zip文件中添加多個文檔?

BOOL isDir=NO; 

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 

NSArray *subpaths; 
for(int i=0; i<[arrdocument count]; i++) 
{ 
    NSString *toCompress = [arrdocument objectAtIndex:i]; 
    NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress]; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){ 
     subpaths = [fileManager subpathsAtPath:pathToCompress]; 
    } else if ([fileManager fileExistsAtPath:pathToCompress]) { 
     subpaths = [NSArray arrayWithObject:pathToCompress]; 
    } 

    NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"myZipFileName2.zip"]; 

    ZipArchive *za = [[ZipArchive alloc] init]; 
    [za CreateZipFile2:zipFilePath]; 

    if (isDir) { 
     for(NSString *path in subpaths){ 
      NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path]; 
      if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){ 
       [za addFileToZip:fullPath newname:path]; 
      } 
     } 
    } else { 
     [za addFileToZip:pathToCompress newname:toCompress]; 
    } 
} 

但是,當我看到zip文件時,它只顯示了zip文件中的一個文件?

回答

1

看來你似乎在每個循環迭代中重新創建zip文件。而應該移動的zip文件的創建出循環或只是指定追加當您創建的zip文件是這樣的:

[za CreateZipFile2:zipFilePath append:YES]; 
+0

順便說一句,你也應該叫CloseZipFile2當您使用完文件。在你的情況下,你必須在循環結束之前添加文件後執行它。 –

+0

先生沒有選擇追加ZipArchive。 –

+0

我有「arrdocument」,我想要添加到zip文件中的文件數組。 建議如果你有另一種方式來做到這一點。 –

0
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *zipFile = [documentsDirectory stringByAppendingPathComponent:@"compressed.zip"]; 
ZipArchive *zip = [[ZipArchive alloc] init]; 
BOOL result = [zip CreateZipFile2:zipFile]; 
if(result){ 
    NSError *error; 
    NSArray *allFiles = arrdocument; 
    for(int index = 0; index<allFiles.count; index++){ 
     id singleFileName = [allFiles objectAtIndex:index]; 
     NSString *singleFilePath = [documentsDirectory stringByAppendingPathComponent:singleFileName]; 
     [zip addFileToZip:singleFilePath newname:singleFileName]; 
    } 
    [zip CloseZipFile2]; 
}else{ 
    [self showErrorMessage:@"Unable to to create zip file. Please try again later" withTitle:@"Error"]; 
} 
+0

它適合我。 –

相關問題