11

Are there Objective-C classes that are equivalent to the ones contained in the Java package java.util.zip?
Is to execute a CLI command the only alternative?

7 Answers 7

32

As of iOS8/OSX10.10 there is a built-in way to create zip archives using NSFileCoordinatorReadingOptions.ForUploading. A simple example of create zip archives without any non-Cocoa dependencies:

public extension NSURL {

    /// Creates a zip archive of the file/folder represented by this URL and returns a references to the zipped file
    ///
    /// - parameter dest: the destination URL; if nil, the destination will be this URL with ".zip" appended
    func zip(dest: NSURL? = nil) throws -> NSURL {
        let destURL = dest ?? self.URLByAppendingPathExtension("zip")

        let fm = NSFileManager.defaultManager()
        var isDir: ObjCBool = false

        let srcDir: NSURL
        let srcDirIsTemporary: Bool
        if let path = self.path where self.fileURL && fm.fileExistsAtPath(path, isDirectory: &isDir) && isDir.boolValue == true {
            // this URL is a directory: just zip it in-place
            srcDir = self
            srcDirIsTemporary = false
        } else {
            // otherwise we need to copy the simple file to a temporary directory in order for
            // NSFileCoordinatorReadingOptions.ForUploading to actually zip it up
            srcDir = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(NSUUID().UUIDString)
            try fm.createDirectoryAtURL(srcDir, withIntermediateDirectories: true, attributes: nil)
            let tmpURL = srcDir.URLByAppendingPathComponent(self.lastPathComponent ?? "file")
            try fm.copyItemAtURL(self, toURL: tmpURL)
            srcDirIsTemporary = true
        }

        let coord = NSFileCoordinator()
        var error: NSError?

        // coordinateReadingItemAtURL is invoked synchronously, but the passed in zippedURL is only valid 
        // for the duration of the block, so it needs to be copied out
        coord.coordinateReadingItemAtURL(srcDir, options: NSFileCoordinatorReadingOptions.ForUploading, error: &error) { (zippedURL: NSURL) -> Void in
            do {
                try fm.copyItemAtURL(zippedURL, toURL: destURL)
            } catch let err {
                error = err as NSError
            }
        }

        if srcDirIsTemporary { try fm.removeItemAtURL(srcDir) }
        if let error = error { throw error }
        return destURL
    }
}

public extension NSData {
    /// Creates a zip archive of this data via a temporary file and returns the zipped contents
    func zip() throws -> NSData {
        let tmpURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(NSUUID().UUIDString)
        try self.writeToURL(tmpURL, options: NSDataWritingOptions.DataWritingAtomic)
        let zipURL = try tmpURL.zip()
        let fm = NSFileManager.defaultManager()
        let zippedData = try NSData(contentsOfURL: zipURL, options: NSDataReadingOptions())
        try fm.removeItemAtURL(tmpURL) // clean up
        try fm.removeItemAtURL(zipURL)
        return zippedData
    }
}
3
  • 3
    This is great, but what about the other way around? That is, having a zip file and then reading its contents as if it is a directory?
    – adib
    Dec 31, 2015 at 4:47
  • 2
    I looked but could not find any similar method to go the other way around. I've up-voted this answer because it is amazing. However, in my Mac app, I instead used NSTask to invoke /usr/bin/zip and /usr/bin/unzip. It is straightforward, offers a lot of documented options to control the behavior, and in my case took less code than this. Feb 26, 2016 at 14:20
  • 1
    Why isn't this approach more widespread? A built-in solution with no need of any extra library you need to maintain, perfect. "Translated" it to objective c and it seems to work as well. Dec 17, 2020 at 7:21
11

Aside from reading and writing zip archives in your own process, there's no shame in using NSTask to run zip and unzip.

1
  • Using this method would allow to not change the code to support new features. I wonder what exactly does Finder when you select a file/directory, and then select "Compress" from the menu. Which executable does Finder uses?
    – apaderno
    Dec 19, 2009 at 6:59
9
3
  • ZipKit seems to better name its methods than ZipArchive (even if I don't understand why it prefixes its addition methods).
    – apaderno
    Dec 18, 2009 at 13:52
  • Prefixing or suffixing category methods help avert name collisions if Apple ever adds a method in Cocoa under the same name. Dec 19, 2009 at 7:17
  • 1
    ZipKit is now at github.com/kolpanic/ZipKit and no longer on bitbucket (shocker)
    – uchuugaka
    Oct 17, 2013 at 0:58
2

Check out http://code.google.com/p/ziparchive/. It's a class for zipping files. Google is your friend!

2

Translated the answer of @marcprux to Objective-C. Please credit his answer if this is of use for you:

NSURL+Compression.h

#import <Foundation/Foundation.h>


@interface NSURL (NSURLExtension)

- (NSURL*)zip;

@end

NSURL+Compression.m

#import "NSURL+Compression.h"


@implementation NSURL (NSURLExtension)


-(NSURL*)zip
{
  BOOL   isDirectory;
  BOOL   hasTempDirectory = FALSE;
  NSURL* sourceURL;

  NSFileManager* fileManager = [NSFileManager defaultManager];
  BOOL           fileExists  = [fileManager fileExistsAtPath:self.path isDirectory:&isDirectory];

  NSURL* destinationURL = [self URLByAppendingPathExtension:@"zip"];

  if(fileExists && isDirectory)
  {
    sourceURL = self;
  }

  else
  {
    sourceURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
    [fileManager createDirectoryAtURL:sourceURL withIntermediateDirectories:TRUE attributes:nil error:nil];

    NSString* pathComponent = self.lastPathComponent ? self.lastPathComponent : @"file";
    [fileManager copyItemAtURL:self toURL:[sourceURL URLByAppendingPathComponent:pathComponent] error:nil];

    hasTempDirectory = TRUE;
  }

  NSFileCoordinator* fileCoordinator = [[NSFileCoordinator alloc] init];

  [fileCoordinator coordinateReadingItemAtURL:sourceURL options:NSFileCoordinatorReadingForUploading error:nil byAccessor:^(NSURL* zippedURL)
   {
    [fileManager copyItemAtURL:zippedURL toURL:destinationURL error:nil];
   }];

  if(hasTempDirectory)
  {
    [fileManager removeItemAtURL:sourceURL error:nil];
  }

  return destinationURL;
}


@end

NSData+Compression.h

#import <Foundation/Foundation.h>


@interface NSData (NSDataExtension)

- (NSData*)zip;

@end

NSData+Compression.m

#import "NSData+Compression.h"
#import "NSURL+Compression.h"


@implementation NSData (NSDataExtension)


// Creates a zip archive of this data via a temporary file and returns the zipped contents
// Swift to objective c from https://stackoverflow.com/a/32723162/
-(NSData*)zip
{
  NSURL* temporaryURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  [self writeToURL:temporaryURL options:NSDataWritingAtomic error:nil];
  NSURL* zipURL = [temporaryURL zip];

  NSFileManager* fileManager = [NSFileManager defaultManager];
  NSData*        zippedData  = [NSData dataWithContentsOfURL:zipURL options:NSDataReadingMapped error:nil];

  [fileManager removeItemAtURL:temporaryURL error:nil];
  [fileManager removeItemAtURL:zipURL error:nil];
  
  return zippedData;
}


@end

Please let me know any improvements.

1

Check out zipzap, my fast zip file I/O library.

0

Also: http://www.cocoadev.com/index.pl?NSDataCategory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.