gpt4 book ai didi

objective-c - 从 Cocoa 应用程序创建 ZIP 存档

转载 作者:太空狗 更新时间:2023-10-30 03:34:12 25 4
gpt4 key购买 nike

是否有与 Java 包 java.util.zip 中包含的对象等效的 Objective-C 类?
执行 CLI 命令是唯一的选择吗?

最佳答案

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

关于objective-c - 从 Cocoa 应用程序创建 ZIP 存档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1928162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com