Posts from August 2009


, , , , , , ,

Compressing directory contents on the iPhone with zlib

I am preparing version 1.1 of Wine Notes which allows users to export their data from their iPhone. I decided to use JSON and flat image files for maximum portability, which left me with a directory of data to export. So, I needed to find a way to compress that directory into a .zip file while preserving the file hierarchy. This seemed like an easy enough task, but it took me a while to track it down, so I've decided to post the solution here.

Follow these steps:

Link libz.dylib to your target in XCode:
http://stackoverflow.com/questions/289274/error-when-import-zlib-in-iphone-sdk/289301#289301

Download ZipArchive

Drag ZipArchive into your XCode project.

Change the following lines at the top of ZipArchive.h:

  #include "../minizip/zip.h"
  #include "../minizip/unzip.h"

to

  #include "zip.h"
  #include "unzip.h"

Delete the following files:

  1. minizip.c
  2. miniunz.c
  3. iowin32.c
  4. iowin32.h

And here is a sample of the code I used in Wine Notes:


BOOL isDir=NO;	
NSArray *subpaths;	
NSString *exportPath = pathForDocumentFileNamed(@"exportData");
NSFileManager *fileManager = [NSFileManager defaultManager];	
if ([fileManager fileExistsAtPath:exportPath isDirectory:&isDir] && isDir){
  subpaths = [fileManager subpathsAtPath:exportPath];
}

NSString *archivePath = pathForDocumentFileNamed(@"exportData.zip");
		
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:archivePath];
for(NSString *path in subpaths){		
  // Only add it if it's not a directory. ZipArchive will take care of those.
  NSString *longPath = [exportPath stringByAppendingPathComponent:path];
  if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && !isDir){
    [archiver addFileToZip:longPath newname:path];		
  }
}

BOOL successCompressing = [archiver CloseZipFile2];

Permalink    Show Comments