How to zip folders in iPhone SDK?

Yogi picture Yogi · Nov 16, 2011 · Viewed 14.1k times · Source

In my Application,I am taking screenshots of image View and then I am saving those screen shots in document folder of the application.Now I want to Email all those images with the same folder structure they are in.Zipping all the folders containing the images and then attaching the zip file to the mail will solve the problem but how can I zip these folders and then attach them to the mail?

Any help is appreciated!

Answer

Robin picture Robin · Nov 25, 2011

I have used this code to create a zip file of the documents directory of my app and it worked

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
BOOL isDir=NO;
NSArray *subpaths;
NSString *exportPath = docDirectory;
NSFileManager *fileManager = [NSFileManager defaultManager];    
if ([fileManager fileExistsAtPath:exportPath isDirectory:&isDir] && isDir){
    subpaths = [fileManager subpathsAtPath:exportPath];
}

NSString *archivePath = [docDirectory stringByAppendingString:@"/test.zip"];

ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:archivePath];
for(NSString *path in subpaths)
{
    NSString *longPath = [exportPath stringByAppendingPathComponent:path];
    if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && !isDir)
    {
        [archiver addFileToZip:longPath newname:path];      
    }
}

if([archiver CloseZipFile2])
    NSLog(@"Success");
else
    NSLog(@"Fail");