Skip to content

Recipes

pixelglow edited this page Apr 28, 2013 · 17 revisions

Writing a new zip file containing a directory:

ZZMutableArchive* newArchive = [ZZMutableArchive archiveWithContentsOfURL:[NSURL fileURLWithPath:@"/tmp/new.zip"]];
[newArchive updateEntries:
 @[
 [ZZArchiveEntry archiveEntryWithDirectoryName:@"folder/"],
 [ZZArchiveEntry archiveEntryWithFileName:@"folder/first.text"
                                 compress:YES
                                dataBlock:^(NSError** error)
  {
      return [@"hello, world" dataUsingEncoding:NSUTF8StringEncoding];
  }]
 ]
                    error:nil];

Unzip an existing zip file to the file system:

NSFileManager* fileManager = [NSFileManager defaultManager];
NSURL* path = [NSURL fileURLWithPath:@"/tmp/old"];
ZZArchive* archive = [ZZArchive archiveWithContentsOfURL:[NSURL fileURLWithPath:@"/tmp/old.zip"]];
for (ZZArchiveEntry* entry in archive.entries)
{
    NSURL* targetPath = [path URLByAppendingPathComponent:entry.fileName];
    
    if (entry.fileMode & S_IFDIR)
        // check if directory bit is set
        [fileManager createDirectoryAtURL:targetPath
              withIntermediateDirectories:YES
                               attributes:nil
                                    error:nil];
    else
    {
        // Some archives don't have a separate entry for each directory and just
        // include the directory's name in the filename. Make sure that directory exists
        // before writing a file into it.
        [fileManager createDirectoryAtURL:[targetPath URLByDeletingLastPathComponent]
              withIntermediateDirectories:YES
                               attributes:nil
                                    error:nil];
        
        [entry.data writeToURL:targetPath
                    atomically:NO];
    }
}
Clone this wiki locally