从Cocoa应用程序创建ZIP存档

时间:2009-12-18 13:21:09

标签: objective-c cocoa zip archive

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

7 个答案:

答案 0 :(得分:12)

除了在您自己的流程中读取和编写zip存档之外,使用NSTask运行zipunzip并不是一件好事。

答案 1 :(得分:11)

从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
    }
}

答案 2 :(得分:9)

答案 3 :(得分:2)

结帐http://code.google.com/p/ziparchive/。这是一个用于压缩文件的类。谷歌是你的朋友!

答案 4 :(得分:1)

answer of @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://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

请让我知道任何改进。

答案 5 :(得分:0)

答案 6 :(得分:0)

查看我的快速zip文件I / O库zipzap