Skip to content

Recipes

Glen Low edited this page Feb 19, 2015 · 17 revisions

Replacing an entry in an existing zip file:

ZZArchive* archive = [ZZArchive archiveWithURL:
    [NSURL fileURLWithPath:@"/tmp/old.zip"]
    error:nil];
NSMutableArray* entries = [archive.entries mutableCopy];
    [entries replaceObjectAtIndex:replacingIndex
                       withObject:
        [ZZArchiveEntry archiveEntryWithFileName:@"replacement.text"
                                        compress:YES
                                       dataBlock:^(NSError** error)
        {
            return [@"see you again, world"
                dataUsingEncoding:NSUTF8StringEncoding];
        }]];
[archive updateEntries:entries
                 error:nil];

Writing a new zip file containing a directory:

ZZArchive* newArchive = [[ZZArchive alloc] initWithURL:
    [NSURL fileURLWithPath:@"/tmp/new.zip"]
    options: @{ZZOpenOptionsCreateIfMissingKey: @YES}
    error:nil];
[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 archiveWithURL:[NSURL fileURLWithPath:@"/tmp/old.zip"] error:nil];
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 newDataWithError:nil] writeToURL:targetPath
                         atomically:NO];
    }
}
Clone this wiki locally