从Cocoa应用程序创建ZIP归档

11

是否存在与Java包java.util.zip中的类相当的Objective-C类?
执行CLI命令是唯一的选择吗?

7个回答

33

从iOS8/OSX10.10开始,可以使用NSFileCoordinatorReadingOptions.ForUploading内置方式创建zip归档文件。以下是一个简单的示例,不需要任何非Cocoa依赖项即可创建zip归档文件:

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
好的,但是反过来呢?也就是说,如果有一个zip文件,那么如何读取它的内容,就像读取一个目录一样? - adib
2
我查看了但没有找到任何类似的方法来实现相反的操作。我已经点赞这个答案,因为它很棒。然而,在我的Mac应用程序中,我使用NSTask来调用/usr/bin/zip和/usr/bin/unzip。这是直接的,提供了许多有文档记录的选项来控制行为,并且在我的情况下所需的代码比这少。 - Jerry Krinock
1
为什么这种方法不普及呢?内置解决方案无需维护任何额外的库,非常完美。我将其翻译成Objective-C,似乎也可以正常工作。 - Bruno Bieri

11

除了在您自己的进程中读取和写入zip档案之外,使用NSTask运行zipunzip是完全可以的。


使用此方法可以不更改代码来支持新功能。我想知道当您选择文件/目录,然后从菜单中选择“压缩”时,Finder实际上是做什么的。Finder使用哪个可执行文件? - apaderno

9

ZipKit似乎比ZipArchive更好地命名了它的方法(即使我不明白为什么要在附加方法前缀中添加)。 - apaderno
在类别方法中添加前缀或后缀可以帮助避免名称冲突,如果苹果在Cocoa中添加了一个同名的方法。 - Peter Hosey
1
ZipKit现在已经迁移到https://github.com/kolpanic/ZipKit,不再使用bitbucket(震惊)。 - uchuugaka

2

2

将@marcprux的答案翻译成Objective-C。如果这对您有用,请注明他的答案:

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://dev59.com/JHI-5IYBdhLWcg3wSGUB#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

请让我知道任何改进。


1

请查看zipzap,我的快速压缩文件I/O库。



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接