
是执行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存档全部内容,希望文章能够帮你解决objective-c – 从Cocoa应用程序创建ZIP存档所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)